今天在做活動分享時發(fā)現(xiàn)一個奇怪的現(xiàn)象。在Twitter、Facebook、WhatsApp、本地分享的鏈接一模一樣的情況下,就WhatsApp出現(xiàn)了參數(shù)被攔截的情況。
舉個例子,分享鏈接為:https://aaaa.erwer/werw?id=1000&host=324324(我亂打的一串,基本上都是這種格式)
然而當你使用WhatsApp分享時會發(fā)現(xiàn)分享的串被截的只剩https://aaaa.erwer/werw?id=1000 “&”以后的字符都被截掉了。
Google上一通搜索發(fā)現(xiàn)了原因:WhatsApp對于字符的編碼。
解決方法就是(用%26代替&)
urlStr = urlStr.replacingOccurrences(of: "&", with: "%26")
然后接著對得到的URL進行處理(防止出現(xiàn)中文訪問不了的情況)
if let newStr = urlStr.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
guard let url = URL(string: newStr) else { return }
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
} else {
fromVC.alertInfo(title: "", msg: YLLocalizedString("title.share.noWhatsApp"))
}
}
然后你以為就可以了嗎????哈哈哈,太天真了。打印發(fā)現(xiàn)還是不行,到底問題出在哪里?打印一下newStr的值你會發(fā)現(xiàn)newStr=https://aaaa.erwer/werw?id=1000%2526host=324324
這是因為經過轉碼以后把“%”也轉換掉了,那這個時候我們希望轉碼的時候排除對“%”的轉碼。那接下來得增加一步操作:
var charSet = CharacterSet.urlQueryAllowed
charSet.insert(charactersIn: "%")
if let newStr = urlStr.addingPercentEncoding(withAllowedCharacters: charSet) {
.......
}
經過這個步驟以后你就會發(fā)現(xiàn)能達到你要的目的。小伙伴們有其它關于國外主流平臺的分享或者登陸問題有不懂得可以留言,我看到就會回復你。