Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
798 views
in Technique[技术] by (71.8m points)

swift - Sharing data between an iOS 8 share extension and main app

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: XCode Target capabilities, App Groups

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,

  1. Is there a solution for this method?
  2. How can I share simple data between the containing app and the share extension? The data is just user credentials for an API.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use NSUserDefaults like this:

Save data:

objc

NSUserDefaults *shared = [[NSUserDefaults alloc] initWithSuiteName:@"group.yougroup"];
[shared setObject:object forKey:@"yourkey"];
[shared synchronize];

swift

let defaults = UserDefaults(suiteName: "group.yourgroup")
defaults?.set(5.9, forKey: "yourKey")

Read data:

objc

NSUserDefaults *shared = [[NSUserDefaults alloc] initWithSuiteName:@"group.yougroup"];
id value = [shared valueForKey:@"yourkey"];
NSLog(@"%@",value);

swift

let defaults = UserDefaults(suiteName: "group.yourgroup")
let x = defaults?.double(forKey: "yourKey")
print(x)

This will work fine!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...