我是Swift的新手,因此我想尝试将http调用包装到一个函数中以供重用,但是由于它需要一个完成块,因此我不确定如何调用它。这是我的代码,
func httpPost(_ path: String, _ parameters: [String: Any], completion:@escaping(_ ret:Any?,_ err:Error?) -> Void){
let headers = [
"Content-Type": "application/json",
"cache-control": "no-cache"
]
let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])
var request = URLRequest(url: URL(string: path)! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData
let session = URLSession.shared
let dataTask = session.dataTask(with: request) { (data, response, error) -> Void in
guard let data = data else {
completion(nil,error)
return
}
do{
try self.validate(response)
let json = try JSONSerialization.jsonObject(with: data, options: [])
completion(json,nil)
}catch{
print(error)
completion(nil,error)
}
}
dataTask.resume()
}
我的问题是如何调用此函数?