Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending Whatsapp message to a specific contact number (Swift Project)

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?

like image 666
Mariah Avatar asked Nov 30 '22 16:11

Mariah


2 Answers

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>
like image 193
Sreekanth Avatar answered Dec 04 '22 23:12

Sreekanth


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.

like image 40
max_ Avatar answered Dec 04 '22 22:12

max_