Sharing image and text to Facebook Messenger with UIActivityViewController failing

时光毁灭记忆、已成空白 提交于 2019-12-01 20:23:52

Try to use UIImage instead NSData. You can convert UIImage to AnyObject and add to your array.

Also look at this question: Sharing image using UIActivityViewController

Lalit kumar
let textShare = "This is my original text."
var shareObject = [AnyObject]()
if textShare != nil {
    shareObject.append(textShare as AnyObject)
}

let Yourimage = UIImage(named: "image.png")
let imageData = UIImagePNGRepresentation(Yourimage!) as NSData? 

if let data = imageData {
    shareObject.append(data)
}

if shareObject.count > 0 { // check condition for text and image
    let activityViewController = UIActivityViewController(activityItems: shareObject, applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view
    present(activityViewController, animated: true, completion: nil)
}

So in the end what was needed was an extra step of converting NSData back into UIImage.

Note, the one issue with this approach of converting NSData back into UIImage is that it produces image quality that is either lossless (i.e. Message and Mail) or lossy (i.e. Notes, Photos, Messenger).

Interestingly Messages, Mail, and a variety of third party sharing apps were quite content sharing the NSData in the UIActivityViewController whereas Messenger would just not tolerate it. (I'd be interested to understand why exactly?)


The changes

From this:

    // Prepare image to share
    let imageShare: NSData
    imageShare = UIImagePNGRepresentation(imageSnapshot)!

To that:

    // Prepare image to share
    let imageShareData: NSData
    imageShareData = UIImagePNGRepresentation(imageSnapshot)!
    let imageShare = UIImage(data: imageShareData)!

The final working code

@IBAction func myButton(sender: UIButton) {

    // Take snapshot of screen
    var imageSnapshot: UIImage!
    UIGraphicsBeginImageContextWithOptions(self.view.frame.size, false, 0)
    self.view.drawViewHierarchyInRect(CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height), afterScreenUpdates: false)
    imageSnapshot = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    // Prepare text to share
    let textShare: String!
    textShare = "This is my original text."

    // Prepare image to share
    let imageShareData: NSData
    imageShareData = UIImagePNGRepresentation(imageSnapshot)!
    let imageShare = UIImage(data: imageShareData)!

    // Share text and image
    let activity = UIActivityViewController(activityItems: [textShare, imageShare], applicationActivities: nil)
    if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
        self.presentViewController(activity, animated: true, completion: nil)
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!