如何从iOS应用程序发送消息联系Whatsapp - Swift

时间:2016-10-05 10:11:52

标签: ios swift whatsapp

我正在尝试将我在Swift中开发的iOS应用程序发送给Whatsapp联系人。但是特定的联系人没有打开,而是whatsApp中的所有联系人都打开了。

到目前为止我的代码 -

func messageViaWhatsApp (sender: AnyObject) {
   let messageBody = "Hello"
    let whatsURL = "whatsapp://send?text=\(messageBody)"
    let whatsAppURL  = NSURL(string: whatsURL.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
    if UIApplication.sharedApplication().canOpenURL(whatsAppURL!)
    {
        UIApplication.sharedApplication().openURL(whatsAppURL!)
    }
    else
    {
        let alert = UIAlertView(title: "Sorry", message: "Your device does not have whatsApp installed ", delegate: nil, cancelButtonTitle: "OK")
    }

}

感谢您的帮助。 XCode - 8.0,Swift 2.3

2 个答案:

答案 0 :(得分:3)

出于安全考虑,Apple不允许您发送给特定联系人。

答案 1 :(得分:0)

试试这个......

let urlWhats = "whatsapp://send?phone=***********&text=***"

var characterSet = CharacterSet.urlQueryAllowed
characterSet.insert(charactersIn: "?&")

 if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters: characterSet){

if let whatsappURL = NSURL(string: urlString) {
                if UIApplication.shared.canOpenURL(whatsappURL as URL){
                    UIApplication.shared.openURL(whatsappURL as URL)
                }
                else {
                    print("Install Whatsapp")

                }
            }
        }
  

注意:国家代码(例如:+91)是打开手机号码聊天

的必填项

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

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