Swift 中请求域名URL中间有中文字,会导致直接崩溃,现给大家一个好地解决方案,支持多参数,中文自动编码,英文则正常。
还是老规矩直接上代码
/// 请求链接是 http://www.ruanman.net/?s=苹果&lookup=
let urlString = "http://www.ruanman.net/"
let queryItem = URLQueryItem(name: "s", value: "苹果")
let queryItem1 = URLQueryItem(name: "lookup", value: "")
let urlComponents = NSURLComponents(string: urlString)!
// 将多参数按照顺序放入数组中
urlComponents.queryItems = [queryItem, queryItem1]
let regURL = urlComponents.url
// 结果是: http://www.ruanman.net/?s=%E8%8B%B9%E6%9E%9C&lookup=