Reputation: 1105
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
Upvotes: 1
Views: 3964
Reputation: 549
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>
Upvotes: 1
Reputation: 86
For security purpose Apple doesn't allow you to send to a particular contact.
Upvotes: 3