Shared User Defaults in iOS

Enable App Groups for both targets

InfectiousGrin
iOS App Development

--

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.

  1. In Xcode’s Project Navigator, Click the `Project Icon`
  2. Select the `Host App` Target
  3. Select the `Capabilities` Tab on the top menu
  4. Toggle the `App Groups` capability
    - If you have not associated a development team you will be prompted to.
  5. Select `+` icon and enter a unique group name such as `group.reverse.company.uri.name`
  6. 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"];

--

--