1

I am trying to send a message from my iOS app developed in Swift to a Whatsapp contact. But the specific contact does not get opened, instead all my contacts in whatsApp open up.

My code so far -

func messageViaWhatsApp (sender: AnyObject) {
   let messageBody = "Hello"
    let whatsURL = "whatsapp://send?text=\(messageBody)"
    let whatsAppURL  = NSURL(string: whatsURL.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
    if UIApplication.sharedApplication().canOpenURL(whatsAppURL!)
    {
        UIApplication.sharedApplication().openURL(whatsAppURL!)
    }
    else
    {
        let alert = UIAlertView(title: "Sorry", message: "Your device does not have whatsApp installed ", delegate: nil, cancelButtonTitle: "OK")
    }

}

Thanks for your help. XCode - 8.0, Swift 2.3

bably
  • 1,065
  • 5
  • 17
  • 27
  • 1
    Possible duplicate of [Sending Whatsapp message to a specific contact number (Swift Project)](http://stackoverflow.com/questions/39687014/sending-whatsapp-message-to-a-specific-contact-number-swift-project) – max_ Oct 05 '16 at 10:14
  • What specific contact? You didn't specified a contact in your code. And if I remember well, WhatsApp removed some time ago the option to choose the contact, but maybe they reinstalled id. – Larme Oct 05 '16 at 10:14

2 Answers2

3

For security purpose Apple doesn't allow you to send to a particular contact.

SANDEEP
  • 86
  • 6
  • Thanks. I also researched and thought so, but wanted a confirmation. If you put it as an answer I will accept it. – bably Oct 05 '16 at 10:22
  • You could please look into this link : whatsapp.com/faq/en/iphone/23559013 for further clarification – SANDEEP Oct 05 '16 at 11:06
1

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>
Sreekanth
  • 549
  • 5
  • 13