[英]What is the best way to share user generated images between host app and today extension
I know that to share data between main app and widget is to use NSUserDefaults or CoreData, but both of them are not recommended way to share images. 我知道要在主应用程序和小部件之间共享数据是使用NSUserDefaults或CoreData,但不建议两者都使用共享图像的方式。 To store user generated images , app should use app's Documents directory but it isn't accessible from widget, then how should the app share the images with it's widget? 要存储用户生成的图像 ,应用程序应使用应用程序的Documents目录,但无法从窗口小部件访问它,那么应用程序应如何与其窗口小部件共享图像?
I used shared app group directory to save the image and access it from both container app as well as extension, here's the code. 我使用共享的应用程序组目录保存图像,并从容器应用程序和扩展名访问它,这是代码。
Save image 保存图片
public func saveImage(image:UIImage){
let fileManager = FileManager.default
let directory = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "yourappgroup")?.appendingPathComponent("yourImagename.jpg")
let imageData = UIImageJPEGRepresentation(image, 1)
fileManager.createFile(atPath: (directory?.path)!, contents: imageData, attributes: nil)
}
Get saved image 获取保存的图像
public func saveImage() -> UIImage {
let fileManager = FileManager.default
if let imagePath = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "yourappgroup")?.appendingPathComponent("yourImagename.jpg").path {
if fileManager.fileExists(atPath: imagePath){
return UIImage(contentsOfFile: imagePath)
}else{
print("No Image")
return nil
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.