7

How to send a message and link to WhatsApp in Swift 3

I'm using this code: Code

Message errore to the console:

...failed for URL: "whatsapp://send?text=Check" - error: "This app is not allowed to query for scheme whatsapp"

Thank you

GURU
  • 323
  • 1
  • 4
  • 12
  • 1
    Possible duplicate of [Sending message to WhatsApp from your app using Swift?](https://stackoverflow.com/questions/32042702/sending-message-to-whatsapp-from-your-app-using-swift) – Mo Abdul-Hameed Jul 14 '17 at 21:32

2 Answers2

17

You should try this:

Note: You must have whatsapp app installed into your device.

Swift 3

var documentInteractionController: UIDocumentInteractionController = UIDocumentInteractionController()

@IBAction func whatsappShareText(_ sender: AnyObject)
{
    let originalString = "First Whatsapp Share"
    let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed)

    let url  = URL(string: "whatsapp://send?text=\(escapedString!)")

    if UIApplication.shared.canOpenURL(url! as URL)
    {
        UIApplication.shared.open(url! as URL, options: [:], completionHandler: nil)
    }
}

@IBAction func whatsappShareLink(_ sender: AnyObject)
{
    let originalString = "https://www.google.co.in"
    let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed)
    let url  = URL(string: "whatsapp://send?text=\(escapedString!)")

    if UIApplication.shared.canOpenURL(url! as URL)
    {
        UIApplication.shared.open(url! as URL, options: [:], completionHandler: nil)
    }
}

Add this code in your app "info.plist"

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>whatsapp</string>
</array>
Pragnesh Vitthani
  • 2,532
  • 20
  • 28
2

Swift 5

Please follow the below steps for sharing on WhatsApp through URL Schemes

  1. Add this code in your app "info.plist"

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

enter image description here

  1. For sharing text and URL

     @IBAction func whatsappShareText(_ sender: AnyObject) {
     let message = "First Whatsapp Share & https://www.google.co.in"
     var queryCharSet = NSCharacterSet.urlQueryAllowed
    
     // if your text message contains special char like **+ and &** then add this line
     queryCharSet.remove(charactersIn: "+&")
    
     if let escapedString = message.addingPercentEncoding(withAllowedCharacters: queryCharSet) {
         if let whatsappURL = URL(string: "whatsapp://send?text=\(escapedString)") {
             if UIApplication.shared.canOpenURL(whatsappURL) {
                 UIApplication.shared.open(whatsappURL, options: [: ], completionHandler: nil)
             } else {
                 debugPrint("please install WhatsApp")
             }
         }
     }
    

    }

Happy Coding!

Nitin
  • 1,383
  • 10
  • 19