发送Whatsapp消息到特定的联系号码(Swift项目)

bnl4lu3b  于 2022-11-21  发布在  Swift
关注(0)|答案(3)|浏览(364)

我正在尝试向存储在全局变量中的收件人号码发送whatsapp消息!
通过使用以下简单代码:

let whatsAppUrl = NSURL(string: "whatsapp:\(globalPhone)")
            
if UIApplication.shared.canOpenURL(whatsAppUrl as! URL) {
    UIApplication.shared.openURL(whatsAppUrl as! URL)
} else {
    let errorAlert = UIAlertView(
        title: "Sorry",
        message: "You can't send a message to this number",
        delegate: self,
        cancelButtonTitle:"Ok"
    )
    errorAlert.show()
}

我总是收到提示信息,这是else的情况!虽然数字总是真的!可能是网址语法错误?
在控制台中:

canOpenURL: failed for URL: "whatsapp:0534260282" -
"This app is not allowed to query for scheme whatsapp"

这是正确的方法吗?或者这种方法只是为了分享,通过Whatsapp发短信?

x6492ojm

x6492ojm1#

试试这个...

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

注意:国家代码(例如:+91)是打开移动的号码聊天的必填项
注意:在info.plist中添加url方案

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

kqlmhetl2#

两个问题。
首先,这不是一个有效的URL方案,URL方案采用identifier://params,因此您需要使用whatsapp://phone_number
其次,苹果现在要求你定义你的应用程序在Info.plist文件中使用哪些外部url方案,嵌套在LSApplicationQueriesSchemes键下。
根据Whatsapp URL方案文档,您实际上无法提供要向其发送消息的联系人的电话号码:是的。
但是,您可以提供您要发送给他们的消息:
whatsapp://send?text=Some%20Text .
请确保文本是按百分比编码的,否则NSURL将无法从提供的字符串创建有效的URL。

djp7away

djp7away3#

如果要发送到特定号码,请使用以下代码:

let whatsAppUrl = NSURL(string: "https://api.whatsapp.com/send?phone=**********&text=******")
    
if UIApplication.shared.canOpenURL(whatsAppUrl as! URL) {
    UIApplication.shared.openURL(whatsAppUrl as! URL)
} else {
    let errorAlert = UIAlertView(
        title: "Sorry",
        message: "You can't send a message to this number",
        delegate: self,
        cancelButtonTitle:"Ok"
    )
    errorAlert.show()
}

这个技巧之所以有效,是因为你不直接调用whatsapp,而是调用浏览器,而这个浏览器可以接收电话号码,并打开whatsapp到所需的电话和所需的文本

相关问题