如何从Swift app打开WhatsApp?

时间:2016-10-01 17:38:45

标签: ios swift whatsapp

我正在使用webview用于我的Swift应用程序,并且我在我的网站上有“在WhatsApp上共享”按钮,该按钮在浏览器上运行良好。但是在iPhone应用程序上,当我点击按钮时,没有任何反应。

如何从我的应用程序打开WhatsApp?我正在使用Xcode 8和iOS 10。

5 个答案:

答案 0 :(得分:8)

我知道这是一个老问题,但以下对我有用(我使用的是xcode 8.3.3和swift 3)。

我在Info.plist中添加了whatsapp查询方案。

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

Info.plist

添加后,以下工作:

let urlString = "whatsapp://send?text=Message to share"

let urlStringEncoded = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

let URL = NSURL(string: urlStringEncoded!)

if UIApplication.shared.canOpenURL(URL! as URL) {
    UIApplication.shared.openURL(URL! as URL)
}

答案 1 :(得分:8)

UIApplication.shared.openURL(URL(string:"https://api.whatsapp.com/send?phone=phoneNumber")!)

phoneNumber不是(+)。

phoneNumber看起来像99455555555

答案 2 :(得分:2)

为此,您应该使用URL方案。

let message = "Message"
let urlWhats = "whatsapp://send?text=\(message)"

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, options: [:], completionHandler: { (Bool) in

            })
        } else {
            // Handle a problem
        }
    }
} 

答案 3 :(得分:2)

对于Swift 4.2和iOS 9 +

let phoneNumber =  "+989160000000"
let appURL = NSURL(string: "https://api.whatsapp.com/send?phone=\(phoneNumber)")!
if UIApplication.shared.canOpenURL(appURL as URL) {
    if #available(iOS 10.0, *) {
        UIApplication.shared.open(appURL as URL, options: [:], completionHandler: nil)
    }
    else {
        UIApplication.shared.openURL(appURL as URL)
    }
}
else {
    // Whatsapp is not installed
}

答案 4 :(得分:0)

这是我在交换机结构中使用的一个简单答案。这会加载whatsApp。我仍然在寻找一种方式来呼叫特定联系人。

case "whatsApp":
        let usefullWhere: String = "whatsapp://?app"//
        let url = NSURL(string: usefullWhere)!
        UIApplication.sharedApplication().openURL(url)