如何编写 returns 响应的 alamofire 请求函数?

How to write alamofire request function that returns the response?

我正在编写一个函数来使用 AlamoFire 调用 POST 请求。我正在传递 URL 和参数。我需要 return 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
                }
            }
        }
    }
}

我想 return 来自此函数的响应字典 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(nil, error.localizedDescription)

func callAPI(params: Dictionary<String, Any>, url: String , completion: @escaping (Dictionary<String,Any>?, String?) -> ()) -> Void { }