Recently, I've been making a simple iOS 8 share extension to understand how the system works. As Apple states in its App Extension Programming Guide:
By default, your containing app and its extensions have no direct access to each other’s containers.
Which means the extension and the containing app do not share data. But in the same page Apple brings a solution:
If you want your containing app and its extensions to be able to share data, use Xcode or the Developer portal to enable app groups for the app and its extensions. Next, register the app group in the portal and specify the app group to use in the containing app.
Then it becomes possible to use NSUserDefaults to share data between the containing app and the extension. This is exactly what I would like to do. But for some reason, it does not work.
In the same page, Apple suggests the standard defaults:
var defaults = NSUserDefaults.standardUserDefaults()
In a WWDC presentation (217), they suggest a common package:
var defaults = NSUserDefaults(suiteName: kDefaultsPackage)
Also, I enabled App Groups for both the containing app target and the extension target, with the same App Group name:
But all this setup is for nothing. I cannot retrieve the data I stored in the containing app, from the extension. It is like two targets are using completely different NSUserDefaults storages.
So,
- Is there a solution for this method?
- How can I share simple data between the containing app and the share extension? The data is just user credentials for an API.
If you have
use
This works for me
In my scenario I'm sharing data between the parent iOS app and WatchKit. I'm using Xcode 6.3.1, iOS Deployment Target 8.3
In your viewDidLoad make sure you synchronize:
Example of a button sending text but of course you can pass whatever:
Then on the other side make sure app group matches:
Then synchronize and cal: (In this case "lblNumber" is an IBOutlet label)
Then if you wanted to set something on this side and sync it back then just do the same thing and synchronize and just make sure the stringForKey that you call on the other side is the same:
Hope this makes sense
You may share data by Following below steps:
1) Select your project -> Select Capabilities tab -> Enable App Groups -> Click on '+' -> paste your bundle Id after 'group.'
2) Select your Extension -> Select Capabilities tab -> Enable App Groups -> Click on '+' -> paste your bundle Id after 'group.'
3) Place below code in your main app for which data you want to share:
4) You may get object in extension:
So apparently it works, only when the group name is used as the suite name for NSUserDefaults.
The documentation says NSUserDefaults.standartUserDefaults() should also work but it does not, and this is probably a bug.
You should use NSUserDefaults like this:
Save data:
objc
swift
Read data:
objc
swift
This will work fine!
I translated in swift foogry's answer and it works!!
Save data:
Read data: