如何在Swift 3中发送消息和链接到WhatsApp?

7

如何在Swift 3中发送消息和链接到WhatsApp

我正在使用以下代码: 代码

将错误信息发送到控制台:

...URL为"whatsapp://send?text=Check"的发送失败-错误:"此应用程序不允许查询whatsapp方案"

谢谢


1
可能是[使用Swift从您的应用程序发送WhatsApp消息?](https://dev59.com/XFwY5IYBdhLWcg3w7rn6)的重复问题。 - Mo Abdul-Hameed
2个回答

17

你应该尝试这个:

注意:你必须在设备中安装 WhatsApp 应用程序。

Swift 3

var documentInteractionController: UIDocumentInteractionController = UIDocumentInteractionController()

@IBAction func whatsappShareText(_ sender: AnyObject)
{
    let originalString = "First Whatsapp Share"
    let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed)

    let url  = URL(string: "whatsapp://send?text=\(escapedString!)")

    if UIApplication.shared.canOpenURL(url! as URL)
    {
        UIApplication.shared.open(url! as URL, options: [:], completionHandler: nil)
    }
}

@IBAction func whatsappShareLink(_ sender: AnyObject)
{
    let originalString = "https://www.google.co.in"
    let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed)
    let url  = URL(string: "whatsapp://send?text=\(escapedString!)")

    if UIApplication.shared.canOpenURL(url! as URL)
    {
        UIApplication.shared.open(url! as URL, options: [:], completionHandler: nil)
    }
}

将此代码添加到您的应用程序 "info.plist" 中

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

2

Swift 5

以下是通过URL Schemes在WhatsApp上分享的步骤:

  1. 将以下代码添加到您的应用程序“info.plist”中

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

enter image description here

  1. For sharing text and URL

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

    }

愉快编码!


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