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

对于我的一个应用程序,我想分享数据到WhatsApp联系人。 我尝试了几个解决scheme,超过了StackOverflow,但不能得到确切的解决scheme。 经过一些试验可以实现我所期望的,所以在这里分享给任何人的未来参考。

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().openURL(url!) } 

注意:文本需要被URL编码。 你可以使用任何开源工具通过互联网或在iOS中使用stringByAddingPercentEncodingWithAllowedCharacters函数。 例如

 var urlString = "Hello Friends, Sharing some data here... !" var urlStringEncoded = urlString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) var url = NSURL(string: "whatsapp://send?text=\(urlStringEncoded!)") 

Swift 3.0

尝试使用此代码访问您的应用程序中的watsapp。 它对我来说是完美的。

 @IBAction func sendButtonAction(_ sender: Any) { let date = Date() let msg = "Hi my dear friends\(date)" let urlWhats = "whatsapp://send?text=\(msg)" if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) { if let whatsappURL = NSURL(string: urlString) { if UIApplication.shared.canOpenURL(whatsappURL as URL) { UIApplication.shared.openURL(whatsappURL as URL) } else { print("please install watsapp") } } } } 

我的代码看起来像这样

 let encodeQuizStr = "Check Out The Quiz With link \n http://www.proprofs.com " let urlQuizStringEncoded = encodeQuizStr.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) guard let whatsAppUrl = NSURL(string: "whatsapp://send?text="+urlQuizStringEncoded!) else { return } if UIApplication.shared.canOpenURL(whatsAppUrl as URL) { if #available(iOS 10.0, *) { print(urlQuizStringEncoded!) UIApplication.shared.open(whatsAppUrl as URL, options: [:], completionHandler: nil) } else { UIApplication.shared.openURL(whatsAppUrl as URL) } } else{ ProjectUtility.AlertWith(self, message: " What's App is Not Available.", Title: "Sorry") } 

工作正常但是当我把这个URL

 ("http://www.proprofs.com/quiz-school/story.php?title=pq-find-out-which-ice-age-character-you-are ") 

那么它不工作请检查Thanks.Help将Appriciated。