swift 升級到5,更新了三方庫,支持的系統(tǒng)也從ios 8 升到了 ios 10 陪拘。
發(fā)現(xiàn)有很多方法過期了。
1.編碼
func urlencode(_ string: String) -> String {
let mstring = string.replacingOccurrences(of: " ", with: "+")
let legalURLCharactersToBeEscaped: CFString = "!*'\"();:@&=+$,/?%#[]% " as CFString
return CFURLCreateStringByAddingPercentEscapes(nil, mstring as CFString?, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String
}
告警如下:
'CFURLCreateStringByAddingPercentEscapes' was deprecated in iOS 9.0: Use [NSString stringByAddingPercentEncodingWithAllowedCharacters:] instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent (since each URL component or subcomponent has different rules for what characters are valid).
修改方法:
func urlencode(_ string: String) -> String {
let mstring = string.replacingOccurrences(of: " ", with: "+")
let set = CharacterSet(charactersIn: "!*'\"();:@&=+$,/?%#[]% ")
return mstring.addingPercentEncoding(withAllowedCharacters: set) ?? ""
}
charactersIn的內容和服務器溝通好纤壁,但在網(wǎng)上也找到了通用的封裝
extension String {
//將原始的url編碼為合法的url
func urlEncoded() -> String {
let encodeUrlString = self.addingPercentEncoding(withAllowedCharacters:
.urlQueryAllowed)
return encodeUrlString ?? ""
}
//將編碼后的url轉換回原始的url
func urlDecoded() -> String {
return self.removingPercentEncoding ?? ""
}
}
app內一頓測試左刽,發(fā)現(xiàn)以上修改方法不行,很多特殊符號沒有編譯酌媒。
最終找到了目前經過很多特殊字符測試都通過的90%完美寫法欠痴。
func urlencode(_ string: String) -> String {
var allowedQueryParamAndKey = NSCharacterSet.urlQueryAllowed
allowedQueryParamAndKey.remove(charactersIn: "!*'\"();:@&=+$,/?%#[]% ")
return string.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey) ?? string
}
如果按你的理解認為這個上面代碼是胡扯八道,其實你不防嘗試一下馍佑。
最開始我搜索信息看到相關的代碼的時候斋否,我直接pass他,都是要加一些未被收錄的字符拭荤,在這里刪除那肯定是錯誤的茵臭,沒想到讓一個不會swift的安卓開發(fā)同事讓嘗試一下,為了讓他死心舅世,我一嘗試旦委,結果竟然是正確的奇徒,我目前也給不了一個合理的解析,這段代碼就是能解決這個問題缨硝。
我們對應的后臺用的是go技術摩钙,對應的解碼是url.go中如下方法:
// QueryUnescape does the inverse transformation of QueryEscape,
// converting each 3-byte encoded substring of the form "%AB" into the
// hex-decoded byte 0xAB.
// It returns an error if any % is not followed by two hexadecimal
// digits.
func QueryUnescape(s string) (string, error) {
return unescape(s, encodeQueryComponent)
}