iosswiftimagemssticker

Swift: How to share dynamic images between main project and messages extension


I am trying to add a stickers extension to my app such that users can create stickers in my app and then use them in messages. However, the file paths seem to be different so I have not been able to just save images to file paths, then load them in the message extensions. Basically, what is the best way to share data between an app and its extension? Especially data that is too large for NSUserDefaults.


Solution

  • You have to enable AppGroups, if you want to share data between your main project and app extension.

    The entire tutorial for enabling it and sharing data can be found here (http://www.theappguruz.com/blog/ios8-app-groups).

    After enabling AppGroups, you can store the created sticker in the shared container like this:

    if let fileManager = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "") 
    {
         let imageName = "imageName" // write your image name here
         let imageLocationUrl = fileManager.appendingPathComponent(imageName)
    
         // for saving image
    
         if let data:Data = UIImagePNGRepresentation(image) {
             do {
                try data.write(to: imageLocationUrl)
             }catch {
                    // couldn't write
             }
         }
    }
    

    For getting the image,

    if let fileManager = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "") 
    {
         let imageName = "imageName" // write your image name here
         let imageLocationUrl = fileManager.appendingPathComponent(imageName)
    
         // for getting image
    
         if let data:Data = Data(contentsOfFile: imageLocationUrl.path) {
            let image = UIImage(data: data, scale: UIScreen.main.scale)
         }
    }