Share image on whatsapp using Swift

∥☆過路亽.° 提交于 2020-02-08 07:06:58

问题


I'm creating an application to share images via social media platforms but on WhatsApp especially. I tried using UIActivityViewController but it doesn't display the WhatsApp option when the sheet is shown. I searched online and found the code below: This shows the WhatsApp option when the sheet is displayed but choosing the WhatsApp option causes the application to crash. This is the code:

let controller = UIDocumentInteractionController()
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true)
let documentDir = path[0] as String

 let imgPath=documentDir.stringByAppendingPathComponent("tmp_flag.png")
 let imageURL = NSURL.fileURLWithPath(imgPath)

  println("Image path :\(imageURL)")

  controller.delegate = self
  controller.UTI = "net.whatsapp.image"
  controller.URL = imageURL!
  controller.presentOpenInMenuFromRect(CGRectZero, inView: self.view, animated: true)

Can anyone spot any error somewhere? If not, does anyone have any idea how to make it work?


回答1:


In Swift 3 use this code

@IBAction func whatsappShareWithImages(_ sender: AnyObject) {
    let urlWhats = "whatsapp://app"
    if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed) {
        if let whatsappURL = URL(string: urlString) {

            if UIApplication.shared.canOpenURL(whatsappURL as URL) {

                if let image = UIImage(named: "whatsappIcon") {
                    if let imageData = UIImageJPEGRepresentation(image, 1.0) {
                        let tempFile = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/whatsAppTmp.wai")
                        do {
                            try imageData.write(to: tempFile, options: .atomic)
                            self.documentInteractionController = UIDocumentInteractionController(url: tempFile)
                            self.documentInteractionController.uti = "net.whatsapp.image"
                            self.documentInteractionController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)

                        } catch {
                            print(error)
                        }
                    }
                }

            } else {
               print("Cannot open whatsapp")
            }
        }
    }

}

Add this code in your app **plist**

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>whatsapp</string>
</array>

You can also refer to small app for reference : https://github.com/nithinbemitk/iOS-Whatsapp-Share




回答2:


You need to make the controller a member variable of the class, because controller must be retained.




回答3:


I would like to share mini class for sharing image on Whatsapp, Instagram, Facebook and activity, it may helps someone..

/* Common steps to use these codes */
// 1- Download FBSharekit for sharing on Facebook
// 2- Copy and Paste the following text to your "info.plist" (anywhere)
/*
    <key>FacebookAppID</key>
    <string>08760425023140553</string> //This is a mock id, you must add your own real app id else it never will work
    <key>FacebookDisplayName</key>
    <string>DoYourBest</string> //Add your real app name here
    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>whatsapp</string>
        <string>instagram</string>
        <string>fbapi</string>
        <string>fb-messenger-share-api</string>
        <string>fbauth2</string>
        <string>fbshareextension</string>
    </array>
*/

import FBSDKShareKit

class ShareHelper: NSObject  {

    static func shareImageViaWhatsapp(image: UIImage, onView: UIView) {
        let urlWhats = "whatsapp://app"
        if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed) {
            if let whatsappURL = URL(string: urlString) {

                if UIApplication.shared.canOpenURL(whatsappURL as URL) {

                    guard let imageData = image.pngData() else { debugPrint("Cannot convert image to data!"); return }

                    let tempFile = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/whatsAppTmp.wai")
                    do {
                        try imageData.write(to: tempFile, options: .atomic)
                        self.documentInteractionController = UIDocumentInteractionController(url: tempFile)
                        self.documentInteractionController.uti = "net.whatsapp.image"
                        self.documentInteractionController.presentOpenInMenu(from: CGRect.zero, in: onView, animated: true)

                    } catch {
                        self.callAlertView(title: NSLocalizedString("information", comment: ""),
                                           message: "There was an error while processing, please contact our support team.",
                                           buttonText: "Close", fromViewController: topViewController!)
                        return
                    }

                } else {
                    self.callAlertView(title: NSLocalizedString("warning", comment: ""),
                                       message: "Cannot open Whatsapp, be sure Whatsapp is installed on your device.",
                                       buttonText: "Close", fromViewController: topViewController!)
                }
            }
        }
    }

    static func shareImageViaInstagram(image: UIImage, onView: UIView) {
        let urlWhats = "instagram://app"
        if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed) {
            if let whatsappURL = URL(string: urlString) {

                if UIApplication.shared.canOpenURL(whatsappURL as URL) {

                    guard let imageData = image.pngData() else { debugPrint("Cannot convert image to data!"); return }

                    let tempFile = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/fitbestPhoto.igo")
                    do {
                        try imageData.write(to: tempFile, options: .atomic)
                        self.documentInteractionController = UIDocumentInteractionController(url: tempFile)
                        self.documentInteractionController.uti = "com.instagram.exclusivegram"
                        self.documentInteractionController.presentOpenInMenu(from: CGRect.zero, in: onView, animated: true)

                    } catch {
                        self.callAlertView(title: NSLocalizedString("information", comment: ""),
                                           message: "There was an error while processing, please contact our support team.",
                                           buttonText: "Close", fromViewController: topViewController!)
                        return
                    }

                } else {
                    self.callAlertView(title: NSLocalizedString("warning", comment: ""),
                                       message: "Cannot open Instagram, be sure Instagram is installed on your device.",
                                       buttonText: "Close", fromViewController: topViewController!)
                }
            }
        }
    }

    static func shareImageViaFacebook(image: UIImage, fromViewController: UIViewController) {

        let sharePhoto = FBSDKSharePhoto()
        sharePhoto.image = image
        sharePhoto.isUserGenerated = true

        let content = FBSDKSharePhotoContent()
        content.photos = [sharePhoto]

        let dialog = FBSDKShareDialog()
        dialog.delegate = (fromViewController as! FBSDKSharingDelegate)
        dialog.fromViewController = fromViewController
        dialog.shareContent = content
        dialog.mode = .shareSheet
        dialog.show()
    }

    static func shareImageViaActivity(image: UIImage, onView: UIViewController) {
        let vc = UIActivityViewController(activityItems: [image], applicationActivities: [])
        // so that iPads won't crash
        if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
            if let popoverController = vc.popoverPresentationController {
                popoverController.sourceView = onView.view
                popoverController.sourceRect = CGRect(x: onView.view.bounds.midX, y: onView.view.bounds.maxY, width: 0, height: 0)
                popoverController.permittedArrowDirections = []
            }
        }

        // exclude some activity types from the list (optional)
        onView.present(vc, animated: true)

    }
}

NOTE = self.callAlertView(params...) is a method for calling customized UIAlertViewController so you can remove it and put your own logic code there.

////////////////////////////////////////////////////////////////////////

UPDATE = I added sharing video via Whatsapp inside same function it it should changed like this :

/**
 Shares photo or video via Whatsapp app if it's installed on device
 else it will navigate user to App Store Whatsapp page

  - Parameter sender: UIButton to show popup on this component.
  - Variable `isVideoMode`: Define var as `Bool` to specify type of sharing content.
  - Used functions: `getVideoData()` it's simple func converting video url to data
  - Used function: `CommonUtils.callAlertView(...)` it's simple func shows alert popup
*/
private func shareViaWhatsapp(sender: UIButton) {
    let urlWhats = "whatsapp://app"
    if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed) {
        if let whatsappURL = URL(string: urlString) {

            if UIApplication.shared.canOpenURL(whatsappURL as URL) {

                let mediaData = isVideoMode ? getVideoData() : self.sharingImage?.jpegData(compressionQuality: 1.0)
                let filepath: String = isVideoMode ? "Documents/whatsAppTmp.wam" : "Documents/whatsAppTmp.wai"
                let tempFile = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent(filepath)
                let uti: String = isVideoMode ? "net.whatsapp.movie" : "net.whatsapp.image"

                if let mediaData = mediaData {

                    do {
                        try mediaData.write(to: tempFile, options: .atomic)
                        self.docIntController = UIDocumentInteractionController(url: tempFile)
                        self.docIntController?.uti = uti
                        self.docIntController?.presentOpenInMenu(from: .zero, in: sender, animated: true)

                    } catch let error {

                        CommonUtils.callAlertView(title: NSLocalizedString("information", comment: ""),
                                                  message: "There was an error while processing due to :\(error.localizedDescription)",
                                                  buttonText: "Close", fromViewController: self)
                        return
                    }
                }


            } else {
                let storeUrlString = "https://itunes.apple.com/in/app/whatsapp-messenger/id310633997?mt=8"
                UIApplication.shared.open(URL(string: storeUrlString)!, options: [:], completionHandler: nil)
            }
        }
    }
}


来源:https://stackoverflow.com/questions/28492869/share-image-on-whatsapp-using-swift

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