示例代码:
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>
面临的问题是与 & 共享链接时文本不在 &
之后对于上面的网址文本,就像 http://Hello/site/link?id=MTk=
提前致谢
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
尝试直接初始化为 URL 而不是 NSURL
let whatsappURL = URL(string: urlString)
也许可以使用完成处理程序来进一步调试
UIApplication.shared.open(whatsappURL, options: [:], completionHandler: nil)
经过一些研究和测试,我发现在 .urlQueryAllowed
中使用
AllowedCharacters
时,将允许 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)
}
}
}
对于那些在 flutter web 上的 Whatsapp 中遇到相同问题的人可以使用以下代码片段。
非工作方法❌:
final String _siteLink = "http://clientsite/products?id=2&vc=premium";
String _whatsappLink = "https://api.whatsapp.com/send?text=${_siteLink}";
await launchUrl(_whatsappLink);
OUTPUT:
http://clientsite/products?id=2 //&vc=premium is removed when opening whatsapp web page
工作方法✅:
final Uri _whatsappURI = Uri(
scheme: 'https',
host: 'api.whatsapp.com',
path: 'send',
queryParameters: <String, String>{
'text': _siteLink,
},
);
await launchUrl(_whatsappURI.toString());
OUTPUT:
http://clientsite/products?id=2&vc=premium