swift 升级到5,更新了三方库,支持的系统也从ios 8 升到了 ios 10 。
发现有很多方法过期了。
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的内容和服务器沟通好,但在网上也找到了通用的封装
extension String {
//将原始的url编码为合法的url
func urlEncoded() -> String {
let encodeUrlString = self.addingPercentEncoding(withAllowedCharacters:
.urlQueryAllowed)
return encodeUrlString ?? ""
}
//将编码后的url转换回原始的url
func urlDecoded() -> String {
return self.removingPercentEncoding ?? ""
}
}
app内一顿测试,发现以上修改方法不行,很多特殊符号没有编译。
最终找到了目前经过很多特殊字符测试都通过的90%完美写法。
func urlencode(_ string: String) -> String {
var allowedQueryParamAndKey = NSCharacterSet.urlQueryAllowed
allowedQueryParamAndKey.remove(charactersIn: "!*'\"();:@&=+$,/?%#[]% ")
return string.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey) ?? string
}
如果按你的理解认为这个上面代码是胡扯八道,其实你不防尝试一下。
最开始我搜索信息看到相关的代码的时候,我直接pass他,都是要加一些未被收录的字符,在这里删除那肯定是错误的,没想到让一个不会swift的安卓开发同事让尝试一下,为了让他死心,我一尝试,结果竟然是正确的,我目前也给不了一个合理的解析,这段代码就是能解决这个问题。
我们对应的后台用的是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)
}