Ios 使用Swift在whatsapp上共享图像

Ios 使用Swift在whatsapp上共享图像,ios,swift,uidocumentinteraction,Ios,Swift,Uidocumentinteraction,我正在创建一个通过社交媒体平台共享图像的应用程序,特别是在WhatsApp上。我尝试使用UIActivityViewController,但在显示工作表时它不显示WhatsApp选项。我在网上搜索了一下,找到了下面的代码:当显示工作表时,这会显示WhatsApp选项,但选择WhatsApp选项会导致应用程序崩溃。代码如下: let controller = UIDocumentInteractionController() let path = NSSearchPathForDirectorie

我正在创建一个通过社交媒体平台共享图像的应用程序,特别是在WhatsApp上。我尝试使用UIActivityViewController,但在显示工作表时它不显示WhatsApp选项。我在网上搜索了一下,找到了下面的代码:当显示工作表时,这会显示WhatsApp选项,但选择WhatsApp选项会导致应用程序崩溃。代码如下:

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)

有人能在某处发现错误吗?如果没有,是否有人知道如何使其工作?

您需要使控制器成为类的成员变量,因为控制器必须保留。

您需要使控制器成为类的成员变量,因为控制器必须保留。

在Swift 3中使用此代码

@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")
            }
        }
    }

}
在应用程序**plist中添加此代码**


您也可以参考小应用程序:在Swift 3中使用此代码

@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")
            }
        }
    }

}
在应用程序**plist中添加此代码**


你也可以参考小应用:

我想在Whatsapp、Instagram、Facebook和activity上分享图片的迷你课堂,它可能会帮助别人

/* 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)

    }
}

我想分享在Whatsapp、Instagram、Facebook和activity上分享图片的迷你课程,它可能会帮助某人

/* 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)

    }
}

如果它崩溃了,错误消息是什么?当我点击whatsapp图标时,没有错误消息,我的应用程序只是关闭了。就这样。如果你有任何解决方案,请告诉我。thanksI已经为在Whatsapp、Facebook、Instagram和活动上共享图像创建了一个要点,使用Swift 4+编写,这里是一个如果崩溃,错误消息是什么?当我单击Whatsapp图标时,没有错误消息,我的应用程序只是关闭了。就这样。如果您有任何解决方案,请告诉我。thanksI已经为在Whatsapp、Facebook、Instagram和活动上共享图像创建了一个要点,使用Swift 4+编写,下面是一个