在iOS 8共享扩展程序和主应用程序之间共享数据 [英] Sharing data between an iOS 8 share extension and main app
问题描述
最近,我一直在制作一个简单的iOS 8共享扩展程序,以了解系统的工作原理。正如Apple在其应用扩展编程指南:
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.
这意味着扩展程序和包含应用程序不共享数据。但是在同一页面上,Apple提供了一个解决方案:
Which means the extension and the containing app do not share data. But in the same page Apple brings a solution:
如果您希望包含应用及其扩展能够共享数据,请使用Xcode或者是开发人员门户,以便为应用及其扩展启用应用组。接下来,在门户网站中注册应用程序组,并指定要在包含的应用程序中使用的应用程序组。
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.
然后就可以使用了NSUserDefaults在包含应用程序和扩展程序之间共享数据。这正是我想要做的。但由于某种原因,它不起作用。
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.
在同一页面中,Apple建议标准默认值:
In the same page, Apple suggests the standard defaults:
var defaults = NSUserDefaults.standardUserDefaults()
在WWDC中演示文稿(217),他们建议一个共同的包:
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:
但所有这种设置是无用的。我无法从扩展程序中检索存储在包含应用程序中的数据。这就像两个目标使用完全不同的NSUserDefaults存储。
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.
所以,
- 这种方法有解决方案吗?
- 如何在包含应用和共享扩展之间共享简单数据?数据只是API的用户凭据。
推荐答案
您应该使用NSUserDefaults,如下所示:
You should use NSUserDefaults like this:
保存数据
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")
读取数据:
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)
这样可以正常使用!
这篇关于在iOS 8共享扩展程序和主应用程序之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!