如何从方法返回alamofire Http请求的结果?

时间:2017-05-26 07:51:16

标签: swift httprequest alamofire completion

我正在使用alamofire和swift 3.我想返回从Http请求获得的数据。目前我正在使用完成处理程序。

func SendHttpRequest(params: AnyObject, header_obj: [String: String], url:String, http_method:HTTPMethod, completion: @escaping (_ response_value: JSON, _ error_type: String)->()) {

        Alamofire.request(BASE_URL + url, method: http_method, parameters: (params as! [String : Any]) , encoding: URLEncoding.default, headers: header_obj).responseJSON { (response:DataResponse<Any>) in

            switch(response.result) {
            case .success( _ ):

                if let jsonValue = response.result.value {
                    let json = JSON(jsonValue)
                    completion(json, "")
                }
                break

            case .failure(_):
                print(response.result.error!)
                completion(JSON(response.result.value!), "NO_INT")
                //"The Internet connection appears to be offline."
                break

            }
        }//Alamofire

    }//SendHttpRequest

但我想要的是返回我通过Http请求获得的结果。 例如: -

func GetUsers() -> [Users]{
   //HERE IT SHOULD EXCUTE THE HTTP REQUEST AND RETURN THE USERS LIST
}

我怎样才能实现它?我能像方法传递一样实现它作为参数理论吗?

1 个答案:

答案 0 :(得分:1)

我并不确定你的json是如何构建的,或者你的用户结构/类看起来如何,但是你应该这样做类似的东西。如果我理解你想做什么。

 class NetworkingStuff {
        func SendHttpRequest(params: AnyObject, header_obj: [String: String], url:String, http_method:HTTPMethod, success:  @escaping (Any) -> (), failure: @escaping (error?) -> ()) {

                Alamofire.request(BASE_URL + url, method: http_method, parameters: (params as! [String : Any]) , encoding: URLEncoding.default, headers: header_obj).responseJSON { (response:DataResponse<Any>) in

                    switch(response.result) {
                    case .success( _ ):

                        if let jsonValue = response.result.value {
                            let json = JSON(jsonValue)
                            success(json, "")
                        }
                        break

                    case .failure(_):
                        print(response.result.error!)
                        failure(JSON(response.result.value!), "NO_INT")
                        //"The Internet connection appears to be offline."
                        break

                    }
                }
            }
        }

处理数据:

  func GetUsers() -> [Users]? {
       networkingStuff.sendHttpRequest(params: something, header_obj: dict, url: URL, http_method: Alamofire.post, success: { (responseData: Any) -> () in
              if let data = responseData as? [String: Any], let users = data["users"] as? [String: Any] {
                  if let userArray = Users(dict: users) {
                      return userArray
                  } else {
                      return nil
                  }
              }

        }, failure: { (error: Any?) -> () in
            return nil
        })
    }