关于共享数据:
如果您想在 iOS8 扩展和包含应用程序之间共享文件,您需要将文件写入共享容器或使用共享用户默认值。
来自Apple的iOS8当前文档:
默认情况下,您的包含应用程序及其扩展没有直接的
访问彼此的容器
您想要创建一个应用程序组,并将包含您的应用程序及其扩展添加到该组。使用 Xcode 6 这非常简单,以下是在 Xcode 中执行此操作的方法:
在应用程序组名称中,输入一个常量,例如:
group.com.bundle.app.soething
这将为您包含的应用程序和扩展创建一个共享容器,它允许:
-
分享 NSUserDefaults:
[[NSUserDefaults alloc] initWithSuiteName:@"group.com.bundle.app.soething"];
-
在文件系统上共享目录:
NSURL *containerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.com.bundle.app.soething"];
编辑
这将打印出我们拥有的所有路径组合:
// App group's path
NSURL *containerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.com.test.app"];
NSLog(@"App group: %@", containerURL.path);
// Bundle path
NSLog (@"Bundle: %@", [[NSBundle mainBundle] bundlePath]);
// Good old Documents path
NSArray *Paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [Paths objectAtIndex:0];
NSLog(@"Documents: %@ ", path);
编辑 - 对于 Swift:
-
分享 NSUserDefaults:
var sharedDefaults = NSUserDefaults(suiteName: "group.com.bundle.app.soething")
-
在文件系统上共享目录:
var containerURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.com.bundle.app.soething")!
我希望这可以帮助你 :)
资源:
苹果iOS8.0扩展开发指南-https://developer.apple.com/library/content/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW1 https://developer.apple.com/library/content/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW1
Apple 的 iOS8.0 NSFileManager 类参考 -https://developer.apple.com/documentation/foundation/nsfilemanager/1412643-containerurlforsecurityapplicati https://developer.apple.com/documentation/foundation/nsfilemanager/1412643-containerurlforsecurityapplicati