小编典典

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

swift

对于我的一个应用程序,我想与WhatsApp联系人共享数据。我在StackOverflow上尝试了一些解决方案,但无法获得确切的解决方案。经过一些试验可以达到我的期望,因此在这里分享以供将来参考。


阅读 378

收藏
2020-07-07

共1个答案

小编典典

 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编码。您可以使用Internet上的任何开源工具或使用iOS中的addPercentEncoding(withAllowedCharacters
:)函数来获取它。例如

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