Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open WhatsApp from Swift app?

I am using webview for my Swift app and I have "Share on WhatsApp" button on my website which works fine on a browser. But on iPhone app, when I click on the button, nothing happens.

How to open WhatsApp from my app? I am using Xcode 8 and iOS 10.

like image 349
Ninder Chand Avatar asked Oct 01 '16 17:10

Ninder Chand


Video Answer


3 Answers

For Swift 4.2+ and iOS 9+

Method 1: (launches WhatsApp application if is installed)

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)
    }
}

Method 2:(open WhatsApp short-link web page using safari)

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)
    }
}

Note : '+' in phone number is OK.

like image 94
Sabrina Avatar answered Sep 29 '22 21:09

Sabrina


I know this is an old question, but the following worked for me (I'm using xcode 8.3.3 and swift 3).

I added whatsapp query scheme inside Info.plist.

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>whatsapp</string>
</array>

Info.plist

After adding it, the following works:

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)
}
like image 29
Leonardo Ferreira Avatar answered Sep 29 '22 21:09

Leonardo Ferreira


UIApplication.shared.openURL(URL(string:"https://api.whatsapp.com/send?phone=phoneNumber")!)

phoneNumber might be with (+) or not.

phoneNumber looks like 99455555555 or +99455555555

like image 21
ElvinM Avatar answered Sep 29 '22 20:09

ElvinM