在 iPhone 和 Watch 应用程序中共享文档目录中的数据

Sharing data in the documents directory in iPhone and Watch app

如何使用应用组共享文档目录中的数据,例如图像?

如果这不可能,那么在 Watch 应用程序和 iPhone 应用程序之间共享图像的最佳方式是什么?我可以将图像二进制数据存储在 coredata 中,但这不是很有效。我也可以使用 NSUserDefaults 完成此操作,但同样效率不高。

Share data with App Groups.

Easily share small amounts of data between your iOS app and your WatchKit extension with App Groups and NSUserDefaults. For access to other resources, such as a Core Data store, use a shared container between your iOS app and your WatchKit extension to simplify data access and provide up to date information.

看看 WatchKitt App Architecture

在 Xcode 中配置应用组后(参见 Sharing Data with Your Containing iOS App 部分),您可以获得共享 container/folder 的路径,如下所示:

NSURL *groupContainerURL = [[NSFileManager defaultManager]
            containerURLForSecurityApplicationGroupIdentifier:@"YourAppGroupIdentifier"];
NSString *sharedDirectory = [groupContainerURL path];

然后,将 UIImage(例如)写入该文件夹:

NSData *imageData = UIImagePNGRepresentation(image);
NSString *filePath = [sharedDirectory stringByAppendingPathComponent:@"image.png"];
[imageData writeToFile:filePath atomically:YES];

您可以在 Watch 扩展程序和 iOS 应用程序中使用相同的逻辑来共享文件。您也可以创建自己的目录,因为共享容器没有 "standard" 目录结构。