For Swift 4.2+ and iOS 9+
Method 1: (Launches WhatsApp app if 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.
You can combine both methods:
func createWhatsappURL(phoneNumber: String) -> URL {
return URL(string: "https://api.whatsapp.com/send?phone=\(phoneNumber)")!
}
func createWebWhatsappURL(phoneNumber: String) -> URL {
return URL(string: "https://wa.me/\(phoneNumber)")!
}
func openURL(_ url: URL) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
func openWhatsapp(withPhoneNumber phoneNumber: String) {
let appURL = createWhatsappURL(phoneNumber: phoneNumber)
let webURL = createWebWhatsappURL(phoneNumber: phoneNumber)
if UIApplication.shared.canOpenURL(appURL) {
openURL(appURL)
} else {
openURL(webURL)
}
}
// usage
let phoneNumber = "+989160000000" // you need to change this number
openWhatsapp(withPhoneNumber: phoneNumber)