Swift 解决URL或参数中含有中文(Swift URL编码)

Swift 解决URL或参数中含有中文(Swift URL编码)

========================

1
2
let encodeURLStr = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url = URL.init(string: encodeURLStr)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
static func get( _ url: String, parameters: [String: Any] , completionHandler: @escaping (NSError?, JSON) -> Void)  {

var urlStr = url
var flag = true
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowedCharacterSet = CharacterSet.urlQueryAllowed
allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
for ( key , value) in parameters {

var anyValue: Any = value
if let value = value as? String{

anyValue = value.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? ""
}

if flag{
flag = false
urlStr += "?" + key + "=\(anyValue)"
}else{
urlStr += "&" + key + "=\(anyValue)"
}
}
if let url = URL.init(string: urlStr){
var request = URLRequest(url: url)
request.cachePolicy = .reloadIgnoringLocalCacheData

URLSession.shared.dataTask(with: request, completionHandler: { (data, response, err) in

if let err = err{

completionHandler(err as NSError, JSON.null )
}else{
// if let json = try? JSONSerialization.jsonObject(with: data!, options: [.allowFragments, .mutableContainers , .mutableLeaves]) as? [String: Any] {
if let data = data {
let json = JSON.init(data: data)
guard let code = json["code"].int,
let msg = json["msg"].string else{
completionHandler(NSError(domain: "", code: 1, userInfo: nil), JSON.null)
return
}

if code != 10000 {

completionHandler(NSError(domain: msg, code: code, userInfo: nil), JSON.null )
}else{

completionHandler(nil, json["data"])
}
}
}


})
.resume()
}
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!