I'm trying to send a whatsapp message to a recipient number stored in a global variable!
By using this simple code:
let whatsAppUrl = NSURL(string: "whatsapp:\(globalPhone)")
if UIApplication.shared.canOpenURL(whatsAppUrl as! URL) {
UIApplication.shared.openURL(whatsAppUrl as! URL)
} else {
let errorAlert = UIAlertView(
title: "Sorry",
message: "You can't send a message to this number",
delegate: self,
cancelButtonTitle:"Ok"
)
errorAlert.show()
}
I'm always getting the alert message which's the else case! although the number is always true! May be the the error in the url syntax?
In the console:
canOpenURL: failed for URL: "whatsapp:0534260282" -
"This app is not allowed to query for scheme whatsapp"
Is this the correct way to do that? Or this way just for sharing, text through Whatsapp?
Try this....
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")
}
}
Note:Country code (Ex:+91) is mandatory to open mobile number Chat
Note: Add url scheme in info.plist
<key>LSApplicationQueriesSchemes</key>
<array>
<string>whatsapp</string>
</array>
Two issues.
The first is that's not a valid url scheme. A URL scheme takes the format identifier://params
so you'll need to use whatsapp://phone_number
instead.
Secondly is that Apple now requires you to define which external url schemes that your application uses in your Info.plist file, nested under the key LSApplicationQueriesSchemes. Please see iOS 9 not opening Instagram app with URL SCHEME for more info.
According to the Whatsapp URL scheme docs, you can't actually supply the phone number of the contact that you'd like to send the message to: https://www.whatsapp.com/faq/en/iphone/23559013.
You can however supply the message that you'd like to send to them:
whatsapp://send?text=Some%20Text
.
Ensure that the text is percentage encoded as otherwise NSURL will fail to create a valid URL from the supplied string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With