swiftxcodeswiftuinsuserdefaultsappgroups

Understanding the relationship between suiteName and App Groups


Background

I'm developing a macOS applications that consists of a plugin and main application. I would like for both targets to be able to share the same settings. I want to manipulate my settings using the Defaults class.

Implementation

Defaults

First I extend the UserDefaults in the following manner:

extension UserDefaults {
    static let group = UserDefaults(suiteName: "the same as app group????")
}

I subsequently create my Defaults class:

import SwiftUI

class Defaults: ObservableObject {
    // Initial set of user settings
    @AppStorage("some_value", store: .group) var someValue: Bool = false
}

I would then conveniently reference values and bidings in that class using

@StateObject var defaults = Defaults()

App Groups

I would then add App Group capability for each of my targets: app Grpup

Background

Puneet, in this useful answer defines suiteName as:

suiteName:is kind of an identifier which helps you create preferences(UserDefaults) store. By using a particular suiteName, you are creating a preferences store, that is not bounded to a particular application (whereas standard UserDefaults are different for every application).

The documentation on implementing App Groups suggest using $(TeamIdentifierPrefix)com.example.mygroup.

Questions

  1. What's the relationship between suiteName and string provided within the App Group field?

  2. Give the product outline (macOS app + plugin), what's the correct implementation:

    a) I should use the same string as App Group value and suiteName.

    b) I should programmatically derive value of $(TeamIdentifierPrefix) and use that as value for suiteName

    c) Value of suiteName should be different from string typed across App Group values.


Solution

  • In order for the UserDefaults to use the AppGroup the suite name has to be the app group identifier. The “standard” suite name is the bundle identifier the group’s suite name is the group identifier.

    TeamIdentifierPrefix is too board IMO, I think it should be appropriate per scope. If it is used by 1 app with multiple extensions use the app's name. If it's used by multiple apps in the same category use something like BusinessNameSocialMedia. It is just an identifier you can name it whatever you want. I think TeamIdentifierPrefix should be used for something where all of the team's apps need access.