swift URL 编码

swift URL 编码,第1张

概述使用value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""无法保证URL 编码成功,于是我参考 Alamofire 的URL编码如下: static func get( _ url: String, parameters: [String: Any] , completionHandler: @escap

使用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 = 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,JsON.null )                  }else{                     completionHandler(nil,Json["data"])                  }               }            }         })            .resume()      }   }
总结

以上是内存溢出为你收集整理的swift URL 编码全部内容,希望文章能够帮你解决swift URL 编码所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1056267.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存