我如何使用App Groups共享数据,例如在文档目录中的图片?
如果这不可行,那么在Watch App和iPhone应用之间共享图片的最佳方法是什么?我可以将图像二进制数据存储在coredata中,但这不太高效。我也可以使用NSUserDefaults来完成此操作,但这也不是很高效。
在您在Xcode中配置了App Group之后(请参阅有关与包含iOS应用程序共享数据的部分),您可以像这样获取共享容器/文件夹的路径:
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];
系统仅会自动创建Library/Caches子目录...
(请参见https://developer.apple.com/documentation/foundation/filemanager/1412643-containerurl)。 - Chris Prince