在iOS11即将发布之际,现在越来越多的开发者开始使用swift语言做开发,swift语言也越来越成熟,最近一段时间,在工作之余对网络请求就swift语言进行了封装。
封装伊始
首先声明一个类继承于AFHTTPSessionManager
class SwiftHttpNetwork: AFHTTPSessionManager
BaseUrl
func setBaseUrl (baseURL:NSString?,timeOutInterval :Double ){
SwiftHttpNetwork._baseURL = baseURL
SwiftHttpNetwork.networkManager = SwiftHttpNetwork.init(baseURL:self.baseURL)
SwiftHttpNetwork.networkManager?.requestSerializer = AFHTTPRequestSerializer()
SwiftHttpNetwork.networkManager?.responseSerializer = AFJSONResponseSerializer.init()
// 信任证书
SwiftHttpNetwork.networkManager?.securityPolicy = AFSecurityPolicy.init(pinningMode: AFSSLPinningMode.none)
SwiftHttpNetwork.networkManager?.securityPolicy.allowInvalidCertificates = true
SwiftHttpNetwork.networkManager?.securityPolicy.validatesDomainName = false
SwiftHttpNetwork.networkManager?.requestSerializer.timeoutInterval = timeOutInterval
let contentTypes: Set = ["application/json", "text/json", "text/javascript","text/html", "application/x-javascript"]
SwiftHttpNetwork.networkManager?.responseSerializer.acceptableContentTypes = contentTypes
}
post请求
今天先为大家介绍一下我们常用的post请求封装,后期会丰富,如果有同仁有好的意见欢迎留言批评指正
class func POST(URLString: String, parameters:Dictionary<String, Any>, completion: @escaping ( _ dataDic: Any ) ->Void, backError:@escaping ( _ error: Error ) ->Void) ->Void {
SwiftHttpNetwork.networkManager = SwiftHttpNetwork.init()
SwiftHttpNetwork.networkManager?.requestSerializer = AFHTTPRequestSerializer()
SwiftHttpNetwork.networkManager?.responseSerializer = AFJSONResponseSerializer.init()
// 信任证书
SwiftHttpNetwork.networkManager?.securityPolicy = AFSecurityPolicy.init(pinningMode: AFSSLPinningMode.none)
SwiftHttpNetwork.networkManager?.securityPolicy.allowInvalidCertificates = true
SwiftHttpNetwork.networkManager?.securityPolicy.validatesDomainName = false
let contentTypes: Set = ["application/json", "text/json", "text/javascript","text/html", "application/x-javascript"]
SwiftHttpNetwork.networkManager?.responseSerializer.acceptableContentTypes = contentTypes
let urlsting :String = kBaseUrlApi + URLString
SwiftHttpNetwork.networkManager?.post(urlsting, parameters: parameters, progress: nil, success: { (task :URLSessionDataTask, data:Any) in
return completion(data)
}, failure: { (task:URLSessionDataTask, error:Error ) in
return backError(error)
} as? (URLSessionDataTask?, Error) -> Void)
}
参考demo:https://github.com/hw2396611405/swiftObject.git
在demo中会持续更新swift一些新特性的使用,比如闭包,函数 欢迎各位关注,star!!!
当然,在这次封装中还有一些冗余代码,可以进一步封装,欢迎各位同仁留言交流