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. 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?
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
}
}