【问题标题】:How to write alamofire request function that returns the response?如何编写返回响应的alamofire请求函数?
【发布时间】:2019-07-30 09:51:29
【问题描述】:

我正在编写一个函数来使用 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 调用重用这个函数。

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

【问题讨论】:

    标签: ios swift alamofire swift4.2


    【解决方案1】:

    你可以像这样将闭包作为参数传递给函数

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

    【讨论】:

    • 谢谢。我更新答案以消除错误。完成后我添加@escaping:
    • git 摆脱 DispatchQueue.global().async {DispatchQueue.main.async {
    • @VinuJacob 正如 Sh_Khan 所说,您不需要 DispatchQueue 块。 Alamofire 请求在后台线程中调用,并在主线程中返回响应
    • @Sh_Khan 谢谢。我会删除它。
    【解决方案2】:

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

    func callAPI(params: Dictionary&lt;String, Any&gt;, url: String , completion: @escaping(Dictionary&lt;String,Any&gt;?, String?) -&gt; ()) -&gt; Void { }

    【讨论】:

      猜你喜欢
      • 2016-04-09
      • 2017-02-15
      • 1970-01-01
      • 1970-01-01
      • 2018-04-19
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多