Search code examples
iosmessagesdwebimageimessage

MSConversation.insertAttachment with UIImage downloaded via SDWebImage


I have an iMessage app that displays some remote content using SDWebImage. The images are downloaded and cached on disk. After choosing an image, I want to attach it to the message as a plain UIImage (not a MSMessage).

Here's the code I'm using

    // image is already downloaded
    let cache = SDImageCache.shared()
    let key = remoteImageUrl
    let fileUrlString = cache.defaultCachePath(forKey: key)!
    let fileUrl = URL(string: fileUrlString)!

    // image holds the correct UIImage
    let image = UIImage(contentsOfFile: fileUrlString)

    activeConversation?.insertAttachment(fileUrl, withAlternateFilename: "a funny gif", completionHandler: { (error) in
        // error is nil here
        print("error: \(error)")
    })

Here's what the message looks like

enter image description here

It seems like the Messages framework can't find the image at that path.

Note: after tapping send, I the iMessage app crashes "MobileSMS quit unexpectedly."


Solution

  • I found out that I needed to use

    let fileUrl = URL(fileURLWithPath: fileUrlString)

    Hope this helps someone else