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

时间:2019-07-30 09:51:29

标签: ios swift alamofire swift4.2

我正在编写一个使用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调用。

如何重写此函数以获取解决方案?

2 个答案:

答案 0 :(得分:1)

您可以将闭包作为参数传递给此类函数

<center><h2>BTC $<?php= price("bitcoin");?></h2></center>
<center><h2>LTC $<?php= price("litecoin");?></h2></center>
<center><h2>XMR $<?php= price("monero");?></h2></center>

使用闭包调用函数

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
        }
    }
}

答案 1 :(得分:0)

您应该传递clouser参数。 此后,如果服务器结果错误,则成功执行completion(resultJson, nil)时应执行completion(nil, error.localizedDescription)

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