Pan*_*wad 13 ios whatsapp swift
对于我的一个应用程序,我想与WhatsApp联系人共享数据.我在StackOverflow上尝试了一些解决方案,但无法获得精确的解决方案.经过一些试验可以实现我想要的,所以在这里分享给任何人的未来参考.
Pan*_*wad 21
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")
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:文本需要进行URL编码.您可以通过互联网使用任何开源工具或在iOS中使用addsPercentEncoding(withAllowedCharacters :)功能来获取它.例如
var urlString = "Hello Friends, Sharing some data here... !"
var urlStringEncoded = urlString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
var url = NSURL(string: "whatsapp://send?text=\(urlStringEncoded!)")
Run Code Online (Sandbox Code Playgroud)
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")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
Addition to above solutions, starting from iOS 9, we need to add whatsapp to LSApplicationQueriesSchemes key in info.plist. After this only it worked for me.
斯威夫特 5
代码
let urlWhats = "whatsapp://send?text=\("Hello World")"
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)
}
else {
print("please install watsapp")
}
}
}
Run Code Online (Sandbox Code Playgroud)