You're developing a macOS application that consists of a main application and a plugin. You want both targets to share the same settings, manipulated using a Defaults class, which extends UserDefaults.
You've extended UserDefaults as follows:
extension UserDefaults {
static let group = UserDefaults(suiteName: "the same as app group????")
}
And created a Defaults class:
import SwiftUI
class Defaults: ObservableObject {
// Initial set of user settings
@AppStorage("some_value", store: .group) var someValue: Bool = false
}
You then reference values and bindings using:
@StateObject var defaults = Defaults()
You've added App Group capability to each of your targets, as shown in the image.
What's the relationship between suiteName and string provided within the App Group field?
The suiteName in UserDefaults(suiteName:) should match the App Group identifier you've set up in your target capabilities. This allows different parts of your app (or different apps in the same group) to access the same set of preferences.
Given the product outline (macOS app + plugin), what's the correct implementation?
The correct implementation is:
a) You should use the same string as the App Group value and suiteName.
Here's why:
group.com.yourcompany.yourappgroup) defines a shared container that both your main app and plugin can access.suiteName when initializing UserDefaults, you're telling your app to use the shared container for storing and retrieving preferences.Correct implementation would look like this:
extension UserDefaults {
static let group = UserDefaults(suiteName: "group.com.yourcompany.yourappgroup")
}
Where "group.com.yourcompany.yourappgroup" is the exact string you've entered in the App Groups capability for both your main app and plugin targets.
The $(TeamIdentifierPrefix) is typically used in the App Group identifier when you're setting it up in Xcode. However, when you're actually using it in code, you should use the full, expanded string.
You can find your full App Group identifier in your Apple Developer account or in Xcode after you've set up the App Groups capability.
Make sure both your main app and plugin have the App Groups entitlement and are part of the same group.
When distributing your app, ensure that the App Group capability is properly set up in your provisioning profiles and that both the main app and plugin are signed with the correct team and provisioning profile.
Remember to handle cases where the shared UserDefaults might not be available (e.g., if the App Group isn't properly set up). You might want to fall back to standard UserDefaults in such cases.