0

示例代码:

let sampleURL = "http://Hello/site/link?id=MTk=&fid=MTA="
let urlWhats = "whatsapp://send?text=\(sampleURL)"
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
   if let whatsappURL = NSURL(string: urlString) {
      if UIApplication.shared.canOpenURL(whatsappURL as URL) {
           UIApplication.shared.open(whatsappURL as URL)
      }
      else {
           // Open App Store.
      }
   }
}

添加在 .plist 文件中

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

面临的问题是在与&共享链接时没有在&之后出现文本

对于上面的 url 文本就像http://Hello/site/link?id=MTk=

提前致谢

4

3 回答 3

1

URL 的不同部分有不同的编码规则。addingPercentEncoding正确使用非常棘手。通常,您不应尝试对自己的 URL 进行编码。让系统使用 URLComponents 为您完成:

//For the constant part of the link, it's fine to just use a string
var sample = URLComponents(string: "whatsapp://send")!

// Then add a query item
sample.queryItems = [URLQueryItem(name: "text", value: "http://Hello/site/link?id=MTk=&fid=MTA=")]

// Extract the URL, which will have the correct encoding
print(sample.url!)
// whatsapp://send?text=http://Hello/site/link?id%3DMTk%3D%26fid%3DMTA%3D
于 2020-08-17T13:20:49.840 回答
0

尝试直接初始化为URL而不是NSURL

let whatsappURL = URL(string: urlString)

并且可能使用完成处理程序来进一步调试

UIApplication.shared.open(whatsappURL, options: [:], completionHandler: nil)
于 2020-08-17T07:14:16.290 回答
0

经过一些研究和测试,我发现在使用.urlQueryAllowedinAllowedCharacters时将允许 URL 并且不会更改 URL,这就是发生此问题的原因。

只需.init()在您的文本上使用如下所示不包含在该编码中,whatsapp://send?text= 如下所示

let sampleURL = "http://Hello/site/link?id=MTk=&fid=MTA="
if let urlString = sampleURL.addingPercentEncoding(withAllowedCharacters: .init()) {
    let urlWhats = "whatsapp://send?text=\(urlString)"
    if let whatsappURL = NSURL(string: urlWhats) {
       if UIApplication.shared.canOpenURL(whatsappURL as URL) {
            UIApplication.shared.open(whatsappURL as URL)
       }
    }
}
于 2020-08-17T09:53:38.790 回答