[英]How to write alamofire request function that returns the response?
我正在编写一个使用AlamoFire调用POST请求的函数。 我正在传递URL和参数。 我需要返回Alamofire请求的响应。
这是我的代码:
func callAPI(params: Dictionary<String, Any>, url: String) -> Void {
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.contentColor = UIColor.red
DispatchQueue.global().async {
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding(options: []), headers: nil).responseJSON { response in
DispatchQueue.main.async {
hud.hide(animated: true)
switch response.result{
case .success:
if let resultJson = response.result.value as? Dictionary<String,Any>{
print(resultJson)
// Success
}
case .failure(let error):
print(error)
//Failed
}
}
}
}
}
我想从该函数返回响应字典resultJson。 我想将此功能用于所有API调用。
如何重写此函数以获取解决方案?
您可以像这样将闭包作为参数传递给函数
func callAPI(params: Dictionary<String, Any>, url: String, completion:@escaping (((Dictionary<String,Any>?) -> Void))) -> Void {
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.contentColor = UIColor.red
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding(options: []), headers: nil).responseJSON { response in
hud.hide(animated: true)
switch response.result{
case .success:
if let resultJson = response.result.value as? Dictionary<String,Any>{
print(resultJson)
completion(resultJson)
// Success
}
case .failure(let error):
print(error)
completion(nil)
//Failed
}
}
}
用闭包调用函数
callAPI(params: [:], url: "") { resultJson in
guard let resultJson = resultJson else {
return
}
print(resultJson)
}
您应该传递clouser参数。 此后,如果服务器结果错误completion(resultJson, nil)
成功执行completion(resultJson, nil)
您应该执行completion(nil, error.localizedDescription)
func callAPI(params: Dictionary<String, Any>, url: String , completion: @escaping
(Dictionary<String,Any>?, String?) -> ()) -> Void { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.