今天只做一個最簡單的網絡封裝。
類型枚舉
enum NetWorkType {
case GET
case POST
}
建立一個工具類,應當繼承自AFHTTPSessionManager
Swift單例寫法
static let shared: NetWorkTools = {
let instance = NetWorkTools()
instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
return instance
}()
封裝,先參照AFN原本參數
override func get(_ URLString: String, parameters: Any?, progress downloadProgress: ((Progress) -> Void)?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)? = nil) -> URLSessionDataTask? {
<#code#>
}
override func post(_ URLString: String, parameters: Any?, progress uploadProgress: ((Progress) -> Void)?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)? = nil) -> URLSessionDataTask? {
<#code#>
}
上面是AFN原請求,注意參數類型
func request(requestType: NetWorkType = .GET, urlString: String, parameters: [String :AnyObject]?, completion: @escaping (_ json: Any?, _ isSuccess: Bool) ->()) {
//成功要進行的回調,參數json,是否成功
let success = { (task: URLSessionDataTask, json: Any?) in
completion(json, true)
}
//成功要進行的回調,參數錯誤信息,可以進行篩選,比如http錯誤碼,對請求進行參照
let failure = { (task: URLSessionDataTask?, error: Error) in
completion(error, false)
}
if requestType == .GET {
get(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
}else{
post(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
}
}
使用
NetWorkTools.shared.request(requestType: .GET, urlString: "http://www.baidu.com", parameters: nil) { (json: Any, success: Bool) in
print(json)
}
同理寫一個上傳文件的,直接上代碼
func uploadWithData(urlString: String, parameters: [String: AnyObject]?, fileData: Data, name: String, fileName: String, progress: @escaping (_ progress: Progress)->(), completion: @escaping (_ json: Any?, _ isSuccess: Bool)->()){
post(urlString, parameters: parameters, constructingBodyWith: { (formData) in
formData.appendPart(withFileData: fileData ,name: name, fileName: fileName, mimeType: "application/octet-stream")
}, progress: { (pro) in
progress(pro)
}, success: { (task: URLSessionDataTask, json: Any?) in
completion(json, true)
}) { (task: URLSessionDataTask?, error: Error) in
completion(error, false)
}
}
用法
NetWorkTools.shared.uploadWithData(urlString: "", parameters: nil, fileData: Data(), name: "", fileName: "", progress: { (progress) in
}) { (json: Any, isSuccess: Bool) in
}
重寫工具類總結:
1.參照工具原參數
2.確定自己需要的回調參數
3.衡量實際需要