swift URL 编码
【swift URL 编码】使用value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
无法保证URL 编码成功,于是我参考 Alamofire 的URL编码如下:
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 = https://www.it610.com/article/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 = .reloadIgnoringLocalCacheDataURLSession.shared.dataTask(with: request, completionHandler: { (data, response, err) inif 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()
}
}
推荐阅读
- Swift中willSet和didSet的简述
- Hacking|Hacking with iOS: SwiftUI Edition - SnowSeeker 项目(一)
- LeetCode算法题-11.|LeetCode算法题-11. 盛最多水的容器(Swift)
- iOS-Swift-map|iOS-Swift-map filter reduce、函数式编程
- Swift|Swift ----viewController 中addChildViewController
- SwiftUI|SwiftUI iOS 瀑布流组件之仿CollectionView不规则图文混合(教程含源码)
- Swift高级应用|Swift高级应用 -01
- Swift5.0|Swift5.0 UITexview的基本使用
- Swift7|Swift7 - 循环、函数
- Swift学习笔记(三)Alamofire二次封装