使用Swift从您的应用程序发送消息到WhatsApp?

20

我的一个应用程序需要将数据分享给WhatsApp联系人。我在StackOverflow上尝试了几个解决方案,但都没有得到确切的解决方案。经过一些尝试,我终于实现了我想要的目标,并在此分享给各位以供参考。

7个回答

26
 var url  = NSURL(string: "whatsapp://send?text=Hello%20Friends%2C%20Sharing%20some%20data%20here...%20!")

//Text which will be shared on WhatsApp is: "Hello Friends, Sharing some data here... !"

    if UIApplication.sharedApplication().canOpenURL(url!) {
        UIApplication.sharedApplication().open(url as URL, options: [:]) { (success) in
                if success {
                    print("WhatsApp accessed successfully")
                } else {
                    print("Error accessing WhatsApp")
                }
            }
    }

注意: 文本需要进行URL编码。你可以使用任何开源工具在互联网上获取它,或者在iOS中使用addingPercentEncoding(withAllowedCharacters:)函数。 例如:

var urlString = "Hello Friends, Sharing some data here... !"
var urlStringEncoded = urlString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
var url  = NSURL(string: "whatsapp://send?text=\(urlStringEncoded!)")

无法找到特定的行,请问在 SWIFT 3 中是哪一行?谢谢。 - Avinash Mishra
@PandurangYachwad,您能告诉我如何在iOS应用程序中使用特定号码打开WhatsApp吗?就像您在这里展示的那样,它将使用一条消息打开WhatsApp,但我想打开WhatsApp的聊天部分并显示特定号码。 - AbaEesa
1
有字符限制吗? - Vaibhav Jhaveri
@VaibhavJhaveri 我认为只要字符格式正确,字符数是没有限制的。 - Pandurang Yachwad
@PandurangYachwad 我的消息被裁剪了。 - Vaibhav Jhaveri
显示剩余11条评论

8

Swift 5

Add whatsapp in LSApplicationQuerySchemes(Info.plist)

代码

let urlWhats = "whatsapp://send?text=\("Hello World")"
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) {
      if let whatsappURL = NSURL(string: urlString) {
            if UIApplication.shared.canOpenURL(whatsappURL as URL) {
                 UIApplication.shared.open(whatsappURL as URL)
             } 
             else {
                 print("please install watsapp")
             }
      }
}

7

Swift 3.0

尝试使用以下代码在您的应用程序中访问 WhatsApp,这对我来说完美地运作。

@IBAction func sendButtonAction(_ sender: Any)
{
    let date = Date()
    let msg = "Hi my dear friends\(date)"
    let urlWhats = "whatsapp://send?text=\(msg)"

    if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) {
        if let whatsappURL = NSURL(string: urlString) {
            if UIApplication.shared.canOpenURL(whatsappURL as URL) {
                UIApplication.shared.openURL(whatsappURL as URL)
            } else {
                print("please install watsapp")
            }
        }
    }
}

有字符限制吗? - Vaibhav Jhaveri
请问您在哪里提到了我需要发送短信的号码? - user9483522

6

除了以上解决方案外,在iOS 9及以上版本中,我们需要在info.plist文件中的LSApplicationQueriesSchemes键中添加whatsapp。只有这样才能让它对我起作用。

解决方案的屏幕截图


2

我的代码看起来像这样

let encodeQuizStr = "Check Out The Quiz With link \n http://www.proprofs.com "

        let urlQuizStringEncoded = encodeQuizStr.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)

        guard let whatsAppUrl = NSURL(string: "whatsapp://send?text="+urlQuizStringEncoded!) else { return }

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

            if #available(iOS 10.0, *) {
                print(urlQuizStringEncoded!)
                UIApplication.shared.open(whatsAppUrl as URL, options: [:], completionHandler: nil)
            } else {

                UIApplication.shared.openURL(whatsAppUrl as URL)

            }
        }
        else{


            ProjectUtility.AlertWith(self, message: " What's App is Not Available.", Title: "Sorry")
        }

工作很好,但当我放置这个URL时

("http://www.proprofs.com/quiz-school/story.php?title=pq-find-out-which-ice-age-character-you-are ")

如果它没有起作用,请检查一下,谢谢。感激您的帮助。


let urlString = "whatsapp://send?text=" + (self.modelForScreen?.deeplinkNarration ?? " ") let urlStringEncoded = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) if let URL = URL(string: urlStringEncoded!), UIApplication.shared.canOpenURL(URL as URL) { UIApplication.shared.open(URL, options: [:], completionHandler: nil) }else{ Utility.showToast("Whatsapp未安装。") } - Umesh Sharma

2

Swift 5

请按照以下步骤通过URL Scheme分享到WhatsApp:

  1. 在您的应用程序“info.plist”中添加此代码

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

在此输入图片描述

  1. 用于分享文本和网址

代码

    @IBAction func whatsappShareText(_ sender: AnyObject) {

    
        let message = "First Whatsapp Share & https://www.google.co.in"
        var queryCharSet = NSCharacterSet.urlQueryAllowed
        
        // if your text message contains special characters like **+ and &** then add this line
        queryCharSet.remove(charactersIn: "+&")
        
        if let escapedString = message.addingPercentEncoding(withAllowedCharacters: queryCharSet) {
            if let whatsappURL = URL(string: "whatsapp://send?text=\(escapedString)") {
                if UIApplication.shared.canOpenURL(whatsappURL) {
                    UIApplication.shared.open(whatsappURL, options: [: ], completionHandler: nil)
                } else {
                    debugPrint("please install WhatsApp")
                }
            }
        }
    }

愉快的编码!


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接