How to init MSSticker using UIImage and not URL?

528 views Asked by At

I'm creating an application that creates stickers dynamically, meaning the user create images in the host app and the sticker shows up dynamically in iMessage stickers.

The way I'm approaching this issue is saving each image in the host app as data (using app group UserDefaults) and then loading them up in the extension app, saving them in the iMessage local directory and then loading them into MSSticker using the url saved:

let sticker = try! MSSticker(contentsOfFileURL: getDocumentsDirectory()!, localizedDescription: "sticker")

However, I want to know if there is a way to load UIImage as stickers without having to save them into local directory first before getting the URL. I've tried saving the UIImage into the host app directory but the host app directory is different from the extension's app directory so this does not work.

1

There are 1 answers

0
Yakov Manshin On

You can save your sticker files to a folder inside the app extension directory, and then get URLs for stickers as follows:

let path = Bundle.main.path(forResource: filename, ofType: "png")! // In this example, stickers are in PNG
let url = URL(fileURLWithPath: path)

You can even create a convenience initializer for MSSticker so you don’t have to copy and paste the code above:

extension MSSticker {
    convenience init(called description: String, from filename: String) {
        let path = Bundle.main.path(forResource: filename, ofType: "png")! // Make sure the specified file exists; otherwise, you’ll get a runtime error.
        let url = URL(fileURLWithPath: path)
        try! self.init(contentsOfFileURL: url, localizedDescription: description) // Unsafe
    }
}

You’ll then be able to create stickers with a single-line expression:

let catSticker = MSSticker(called: "Cat", from: "cat")