如何在Swift中单击Button打开Whatsapp或其他iOS应用程序?

时间:2017-10-06 10:14:40

标签: ios swift

我想从app_A打开iOS app_B,然后想要app_B的数据回到app_A,尝试下面打开whatsapp,但是没有用。请提前感谢您在iOS中如何实现这一目标。

    @IBAction func clickMe(_ sender: UIButton) {

        let url = "https://api.whatsapp.com/send?00919599****** "
        let whatUpUrl = NSURL(string: url)
        if UIApplication.shared.canOpenURL(whatUpUrl! as URL){
            UIApplication.shared.openURL(whatUpUrl! as URL)
        } else {
            //redirect to safari because the user doesn't have Whatsapp installed
            UIApplication.shared.openURL(NSURL(string: "http://whatsapp.com/")! as URL)
        }
    }

2 个答案:

答案 0 :(得分:2)

WebUrl链接打开聊天

let whatsappURL = URL(string: "https://api.whatsapp.com/send?phone=9512347895&text=Invitation")
    if UIApplication.shared.canOpenURL(whatsappURL!) {
        UIApplication.shared.openURL(whatsappURL!)
    }

注意:在info.plist中添加url方案

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

答案 1 :(得分:0)

将此添加到Info.plist

enter image description here

然后在你想要打开的按钮上使用它。

 @IBAction func whatsappButtonPressed(_ sender: Any) {
        var str = "Hello to whatsapp"
        str = str.addingPercentEncoding(withAllowedCharacters: (NSCharacterSet.urlQueryAllowed))!
        let whatsappURL = NSURL(string: "whatsapp://send?text=\(str)")

        if UIApplication.shared.canOpenURL(whatsappURL! as URL) {
            UIApplication.shared.openURL(whatsappURL! as URL)
        } else {
            showAlert(message: "Whatsapp is not installed on this device. Please install Whatsapp and try again.")
        }
}

与其他应用类似: 替换 -      NSURL(字符串:&#34; whatsapp:// send?text =(str)&#34;)with      NSURL(字符串:&#34; APPNAME://&#34;)。 您还需要将该应用程序添加到Info.plist中,如上所述。

谢谢!