iosswiftnsdocumentdirectoryimessage-extensionios-stickers

Unable to display Stickers from Documents directory in iMessage extension


In my app users are able to create images and then use them as stickers in iMessages.

My problem is that I can't display created images that are stored in the Documents Directory.

My issue is very similar to this question - SO Question but in my case the solution stated there didn't help.

Here's my code for fetching images:

 func getImages(finished: () -> Void) {
    imageData.removeAll()
    let imageNames = keyboardUserDefaults!.stringArray(forKey: "Created stickers")
    for imageName in imageNames! {
        //  let imagePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let filePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(imageName)
        // imageData.append(imagePath + "/" + imageName)
        imageData.append(filePath)
    }

    print("Image Data - ", imageData)

    finished()
}

And here is how I apply it to StickerView:

 func configure(usingImageName imagePath: String) {
        let urlToImage = URL(fileURLWithPath: imagePath)
        do {
            let description = NSLocalizedString("", comment: "")
            let sticker = try MSSticker(contentsOfFileURL: urlToImage, localizedDescription: description)

            print("Sicker is here - ", sticker)

            stickerView.sticker = sticker
        }
        catch {
            fatalError("Failed to create sticker: \(error)")
        }
    }

But I'm getting a blank view with no stickers.

Print inside cell shows:

Sicker is here -  <MSSticker-<0x280393640> imageFileURL file:///var/mobile/Containers/Data/PluginKitPlugin/32AF9E44-F2F1-4FD1-80B5-E8E4B6C6E338/Documents/F54067B8-18DA-4737-8ED3-B716E368AF6E.png localizedDescription >

Images are showing when I set them from my folder inside Xcode project using Bundle.main.path, but not from the Documents Directory.


Solution

  • I have found source of my problem:

    Application Extensions can't access default Documents Directory folder.

    Solution:

    Use App Groups and make path for image when saving and retrieving it like this:

    let url = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "YOUR_APP_GROUP_NAME")?.appendingPathComponent("image.png")
    

    After that you can easily access your images in Application Extensions.

    Hope this helps someone in future!