对于iOS代码中用UIWebView加载页面,现在url地址中包含UTF-8的中文
url String “http://xx.xx.xx.xx/skrDev/src/report/wholesale.html?t=1510284914206&drAreaFiltrateCode=大东南区&drAreaFiltrateName=大东南区”; |
然后遇到的现象是:
在调试界面显示的中文不兼容,有\xx出现:
输出的是:&drAreaFiltrateCode=大东南区&drAreaFiltrateName=大\344\270东\345\215南区
在代码调试中,好像是兼容的?
&drAreaFiltrateCode=大东南区&drAreaFiltrateName=大东南区
如图:
然后继续调试,结果发现:
// 加载网络Html页面 请设置允许Http请求 if let url = NSURL(string: self.url) { let request = NSURLRequest(url: url as URL) self.webView.loadRequest(request as URLRequest) } |
NSURL是无法把这种string转化为url的
导致后续代码无法执行。
所以去看看:
iOS NSURL 不支持中文
iOS 解决NSString转换为NSURL时包含中文字符 – CSDN博客
NSURL URLWithString:url 中 中文字符问题(已解决) | iOS开发 – CocoaChina CocoaChina_让移动开发更简单
Xcode提示中,没有找到NSURL支持编码的参数
ios nsurl string encode
ios swift nsurl string encode
How to percent encode a URL String
Encoding and Decoding URL Data
encoding – How to URL encode a NSString – Stack Overflow
ios – How do I URL encode a string – Stack Overflow
swift url utf-8 encode
UTF-8 string encoding (Swift) | dubinski.org
没有stringByAddingPercentEscapesUsingEncoding
URL Decode iOS SWIFT – Stack Overflow
去试试addingPercentEncoding
用:
let encodedUrl:String = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
貌似是可以的。
swift addingPercentEncoding
addingPercentEncoding(withAllowedCharacters:) – NSString | Apple Developer Documentation
Swift3.0语言教程使用URL字符串 – 大学霸 – 博客园
代码:
let encodedUrl:String = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! |
去调试:
编码为我们希望的了:
encodedUrl:
“http://x.x.x.x/skrDev/src/report/wholesale.html?t=1510295408712&drAreaFiltrateCode=%E5%A4%A7%E4%B8%9C%E5%8D%97%E5%8C%BA&drAreaFiltrateName=%E5%A4%A7%E4%B8%9C%E5%8D%97%E5%8C%BA”;
【总结】
此处Swift 3.1中,是可以通过:
let encodedUrl:String = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! |
把原先的带中文的url:
http://xx.xx.xx.xx/skrDev/src/report/wholesale.html?t=1510295408712&drAreaFiltrateCode=大东南区&drAreaFiltrateName=大东南区 |
编码为希望的%xx的:
了,而编码后的%xx的地址,就可以正常的被NSURL去初始化了。
另外再去加上解码,完整库代码为:
extension String { // from // to public var encodedUrl:String { var encodedUrl = self if let addedPercentUrl = self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { encodedUrl = addedPercentUrl } return encodedUrl } // from // to public var decodedUrl:String { var decodedUrl = self if let removedPercentUrl = self.removingPercentEncoding { decodedUrl = removedPercentUrl } return decodedUrl } } |
全部库文件代码详见:
https://github.com/crifan/crifanLib
->
https://github.com/crifan/crifanLib/blob/master/swift/String/CrifanString.swift