Search code examples
swiftxcodemacos-sierratoday-extension

Share data between main app and today widget macOS


I'm trying to share data between my main macOS app and the extension I created.
I saw I have to use the "App Groups" and share the data with "UserDefault(suiteName: "name")"

The problem : After turned on App Groups on the main app and added a name, I then turn on App Groups on extension and the list is empty, I don't see the group I'v just created ?

Any idea ?

btw: the team profil is the same on both app and extension. I'v tried to delete temporary file, clean project, restored Xcode and computer.

enter image description here

EDIT 1 : On iOS project the app groups are detected....
EDIT 2 : I tried with Xcode 9 but same problem.
EDIT 3 : On Certificates, Identifiers & Profiles apple website, you don't have the category "App Groups" for macOS, is it deprecated ??
EDIT 4 : If I add both add groups names manually, then I got an error in output :. [User Defaults] Failed to read values in CFPrefsPlistSource<0x6000000e4200> (Domain: 726328455Z.test, User: kCFPreferencesAnyUser, ByHost: Yes, Container: (null)): Using kCFPreferencesAnyUser with a container is only allowed for System Containers, detaching from cfprefsd.

Edit 5 : Looks like it work, the data is successfully saved with this code

UserDefaults(suiteName: "7263xxx55Z.test")!.set(selectedRow, forKey: "selectedRow")
UserDefaults(suiteName: "7263xxx55Z.test")!.synchronize()

And fetch with this code, I got the previous error but I just ignore it

let selectedRow = UserDefaults(suiteName: "726xxx55Z.test")!.integer(forKey: "selectedRow")

Solution

  • To share data between app/app extension in macOS project :

    1/ In your Main project target, select Capabilities and enable "App Groups".

    2/ Click on "+" and add a new app group name, it must start with your team ID (e.g. 643J438K.name.app)

    3/ Repeat 1/ and 2/ for your extension app target, be sure to add the same name

    4/ To save and fetch data use :

    // Store data
    UserDefaults(suiteName: "643J438K.name.app")!.set(yourVariable, forKey: "yourKey")
    UserDefaults(suiteName: "643J438K.name.app")!.synchronize()
    
    // Fetch data (integer type here)
    UserDefaults(suiteName: "643J438K.name.app")!.integer(forKey: "yourKey")
    

    5/ You can check that your data is correctly saved by opening this file :

    /Users/UserName/Library/Group Containers/643J438K.name.app/Preferences/643J438K.name.app.plist