Shared User Defaults in iOS
Enable App Groups for both targets
Published in
1 min readOct 22, 2014
With the NSUserDefaults class, you can save settings and properties related to application or user data.
While developing extensions in iOS, you may find a need to share application or user data between the host app and the extension.
To do so, you can enable the `App Groups` Capability.
- In Xcode’s Project Navigator, Click the `Project Icon`
- Select the `Host App` Target
- Select the `Capabilities` Tab on the top menu
- Toggle the `App Groups` capability
- If you have not associated a development team you will be prompted to. - Select `+` icon and enter a unique group name such as `group.reverse.company.uri.name`
- Repeat the above for the Extension’s target
You can then use NSUserDefaults initWithSuiteName:.
NSUserDefaults *sharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.example.app"];
Then set a value in one target…
[sharedDefaults setObject:value forKey:@"key"];
[sharedDefaults synchronize];
And read the associated value in the other target…
NSString *value = [sharedDefaults stringForKey:@"key"];