Sending message to WhatsApp from your app using Swift?

前端 未结 6 1285

For one of my app, I wanted to share data to WhatsApp contacts. I tried few solutions overs the StackOverflow but couldn\'t get exact solution. After some trials could achie

6条回答
  •  春和景丽
    2020-12-13 21:13

    Swift 5

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

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

    LSApplicationQueriesSchemes
    
      whatsapp
    

    1. For sharing text and URL

    Code

        @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 characters 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!

提交回复
热议问题