Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing PNG image with UIActivityViewController to Facebook Messenger always fails

This is a question for an expert with specialist knowledge.

It is possible to successfully share high quality lossless PNG images with UIActivityViewController to many sharing platforms with the exception of Facebook Messenger which fails every time. The error provided is “Couldn’t Load Content”.

Both UIImagePNGRepresentation NSData and AnyObject fail in Facebook Messenger, UIImage however shares successfully BUT the outputted image appears to be a JPG and is low quality and lossy.

Question:

What’s going on here and how can it be corrected -- how can I successfully share high quality lossless PNG images with UIActivityViewController to Facebook Messenger?

Is this a problem or limitation of Facebook Messenger, Xcode, or UIActivityViewController?

Are there alternatives to NSData and AnyObject (and UIImage) that will work?

Code:

var myImage: UIImage! 
var myImagePNG: NSData! 
//var myImagePNG: AnyObject!

func sharePNG() { …
    myImagePNG = UIImagePNGRepresentation(myImage)!
    let activity = UIActivityViewController(activityItems: [myImagePNG], applicationActivities: nil)
    self.presentViewController(activity, animated: true, completion: nil)
}

Image:

enter image description here

like image 412
user4806509 Avatar asked Nov 07 '22 19:11

user4806509


1 Answers

The best way to get more control over what gets shared from UIActivityController is not just to encode it to data, but then to write that data to a temporary URL, and then pass the URL to UIActivityController. That way you can control the title of the file being shared, which is important if they choose to save the file or AirDrop it somewhere. If you just share the data you'll end up with some really random filename. This works for sending PNGs via Facebook Messenger:

    enum ImageProcessingError: Error {
        case couldNotCreatePNGData
    }
    
    private func exportImageAsPNG(_ image: UIImage, filename: String) throws {
        guard let pngData = image.pngData() else { throw ImageProcessingError.couldNotCreatePNGData }
        let temporaryURL = FileManager.default.temporaryDirectory
            .appendingPathComponent(filename)
            .appendingPathExtension("png")
        try pngData.write(to: temporaryURL, options: [])
        // present UIActivityViewController with the temporaryURL
    }
like image 184
OliverD Avatar answered Nov 15 '22 11:11

OliverD