【发布时间】:2017-02-10 02:24:30
【问题描述】:
我在我的 Swift 应用程序中使用 webview,并且我的网站上有“在 WhatsApp 上分享”按钮,该按钮在浏览器上运行良好。但是在 iPhone 应用上,当我点击按钮时,什么也没有发生。
如何从我的应用程序中打开 WhatsApp?我正在使用 Xcode 8 和 iOS 10。
【问题讨论】:
我在我的 Swift 应用程序中使用 webview,并且我的网站上有“在 WhatsApp 上分享”按钮,该按钮在浏览器上运行良好。但是在 iPhone 应用上,当我点击按钮时,什么也没有发生。
如何从我的应用程序中打开 WhatsApp?我正在使用 Xcode 8 和 iOS 10。
【问题讨论】:
为此,您应该使用 URL 方案。
let message = "Message"
let urlWhats = "whatsapp://send?text=\(message)"
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, options: [:], completionHandler: { (Bool) in
})
} else {
// Handle a problem
}
}
}
【讨论】:
我知道这是一个老问题,但以下对我有用(我使用的是 xcode 8.3.3 和 swift 3)。
我在 Info.plist 中添加了 whatsapp 查询方案。
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>
添加后,以下工作:
let urlString = "whatsapp://send?text=Message to share"
let urlStringEncoded = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let URL = NSURL(string: urlStringEncoded!)
if UIApplication.shared.canOpenURL(URL! as URL) {
UIApplication.shared.openURL(URL! as URL)
}
【讨论】:
UIApplication.shared.openURL(URL(string:"https://api.whatsapp.com/send?phone=phoneNumber")!)
phoneNumber 可能带 (+) 或不带 (+)。
phoneNumber 看起来像 99455555555 或 +99455555555
【讨论】:
适用于 Swift 4.2+ 和 iOS 9+
方法 1:(如果已安装 WhatsApp 应用程序,则启动)
let phoneNumber = "+989160000000" // you need to change this number
let appURL = URL(string: "https://api.whatsapp.com/send?phone=\(phoneNumber)")!
if UIApplication.shared.canOpenURL(appURL) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(appURL, options: [:], completionHandler: nil)
}
else {
UIApplication.shared.openURL(appURL)
}
}
方法二:(使用safari打开WhatsApp短链接网页)
let phoneNumber = "+989160000000" // you need to change this number
let appURL = URL(string: "https://wa.me/\(phoneNumber)")!
if UIApplication.shared.canOpenURL(appURL) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(appURL, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(appURL)
}
}
注意:电话号码中的“+”是可以的。
【讨论】:
Devs Here is my Code for Opening WhatsApp Chat in Xcode 13.0 and iOS 15.0 for specific Contact.
func navigateToWhatsApp() {
var countryCode = "91". //Country code
var mobileNumber = "1234567890" //Mobile number
let urlString = "https://api.whatsapp.com/send?phone=\(countryCode)\(mobileNumber)"
let urlStringEncoded = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let URL = NSURL(string: urlStringEncoded!)
if UIApplication.shared.canOpenURL(URL! as URL) {
debugPrint("opening Whatsapp")
UIApplication.shared.open(URL as! URL, options: [:]) { status in
debugPrint("Opened WhatsApp Chat")
}
} else {
debugPrint("Can't open")
}
}
【讨论】: