NSUserDefaults, Settings.bundle and App groups

2019-03-27 00:31发布

问题:

I have an app with 2 targets, the main app and a Today extension - to share settings between these targets I've switched on the App Groups Capabilities, added a group group.myApp.com and then using NSUserDefaults like so in both the main app and Today Extension:

var defaults: NSUserDefaults = NSUserDefaults(suiteName: "group.myApp.com")!

(following the instructions here: http://goo.gl/pNrYQl)

This is working fine. I would like to add a Settings.bundle to the app to change settings in both targets but this seems to be using the standardUserDefaults for the 'main' target, not the group.myApp.com section. Any ideas how to make the Settings.bundle use my group.myApp.com settings 'area'?

Many thanks.

回答1:

Eventually found the answer in the comments section of the original linked website.

to target App-Group settings instead of the App Targets user defaults, all you need to do is add “ApplicationGroupContainerIdentifier” as a key to the Root.plist of your Settings Bundle and set its value as your App-Group identifier

So, after adding the following to my Settings.Bundle Root.plist, both my main App and Today Extension are accessing the same user defaults.