Swift URL含有中文解包报错 Thread 1: Fatal error: Unexpectedly found nil while unwrappin

529 阅读1分钟

报错原因:

self.webView.load(URLRequest(url: URL(string: url)!))    此处解包失败

URL(string: url)! 报错位置

###出错url , 因为存在中文

 let url = "http://www.****.com/index.php?m=wap&appid="+APPID+"&city=北京"

###编码

// iOS7 之前
let codeUrl = url.addingPercentEscapes(using: String.Encoding.utf8)
// iOS9 之后
let codeUrl = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!

print("编码过后的url:\(codeUrl)") 

###解码

let decodeUrl = codeUrl.removingPercentEncoding!

print("解码后的url:\(decodeUrl)")