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?
Asked
Active
Viewed 91 times
0
-
try to check with App groups feature. – karthikeyan Jan 21 '17 at 05:18
-
@karthikeyan, that works but it isn't recommended way to store images, so what is the correct method? – Adarsh Urs Jan 21 '17 at 05:21
-
anyway you need to convert image to data, if you are using db.same thing here convert it and use app groups. why its not recommended way? – karthikeyan Jan 21 '17 at 05:24
-
yes, that's what I did, converted image to data to store, I just want to let user set the widget background image so I'm not using db. Should I go with the same approach? – Adarsh Urs Jan 21 '17 at 05:32
-
did you get it image data in widget? if you are plan to multiple image, don't follow this way some one faced problem http://stackoverflow.com/questions/27917538/ios8-extension-share-images-between-container-and-extension – karthikeyan Jan 21 '17 at 05:36
-
if its just a background image, then its ok. http://www.atomicbird.com/blog/sharing-with-app-extensions – karthikeyan Jan 21 '17 at 05:36
-
thanks for the links, I dint know about creating directory in app groups. However if image is too big, even my app widget not loading, I guess using shared documents directory will fix it. – Adarsh Urs Jan 21 '17 at 06:02
-
yes i think so, let me know once you fix.They given example projects also – karthikeyan Jan 21 '17 at 06:13
1 Answers
0
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
}
}

Adarsh Urs
- 112
- 8