如何从Alamofire返回价值 [英] How to return value from Alamofire

查看:113
本文介绍了如何从Alamofire返回价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过使用swift创建的API进行url调用,如下所示:

I am making url calls thru an API that I created using swift as follows:

class API {

  let apiEndPoint = "endpoint"
  let apiUrl:String!
  let consumerKey:String!
  let consumerSecret:String!

  var returnData = [:]

  init(){
    self.apiUrl = "https://myurl.com/"
    self.consumerKey = "my consumer key"
    self.consumerSecret = "my consumer secret"
  }

  func getOrders() -> NSDictionary{
    return makeCall("orders")
  }

  func makeCall(section:String) -> NSDictionary{

    let params = ["consumer_key":"key", "consumer_secret":"secret"]

    Alamofire.request(.GET, "\(self.apiUrl)/\(self.apiEndPoint + section)", parameters: params)
        .authenticate(user: self.consumerKey, password: self.consumerSecret)
        .responseJSON { (request, response, data, error) -> Void in
            println("error \(request)")
            self.returnData = data! as NSDictionary
    }
    return self.returnData
  }

}

我在 UITableViewController 中调用此API以使用SwiftyJSON库填充表。但是,API中的 returnData 始终为空。 Alomofire调用没有问题,因为我可以成功检索值。我的问题是我应该如何将这个数据带到我的表视图控制器上?

I call this API in my UITableViewController to populate the table with SwiftyJSON library. However my returnData from the API is always empty. There is no problem with Alomofire calls as I can successfully retrieve value. My problem is how I am supposed to carry this data over to my table view controller?

var api = API()
api.getOrders()
println(api.returnData) // returnData is empty


推荐答案

正如mattt所指出的,Alamofire是通过 completionHandler 模式异步返回数据,因此您必须执行相同的操作。你不能只是立即返回值,但是你想要使用 Void 返回类型而是使用完成处理程序闭包模式。

As mattt points out, Alamofire is returning data asynchronously via a completionHandler pattern, so you must do the same. You cannot just return the value immediately, but you instead want to use Void return type and instead use a completion handler closure pattern.

在Swift 3和Alamofire 4中,可能看起来像:

In Swift 3 and Alamofire 4, that might look like:

func getOrders(completionHandler: @escaping (NSDictionary?, Error?) -> ()) {
    makeCall("orders", completionHandler: completionHandler)
}

func makeCall(_ section: String, completionHandler: @escaping (NSDictionary?, Error?) -> ()) {
    let params = ["consumer_key":"key", "consumer_secret":"secret"]

    Alamofire.request("\(apiUrl)/\(apiEndPoint + section)", parameters: params)
        .authenticate(user: consumerKey, password: consumerSecret)
        .responseJSON { response in
            switch response.result {
            case .success(let value):
                completionHandler(value as? NSDictionary, nil)
            case .failure(let error):
                completionHandler(nil, error)
            }
    }
}

然后,当你想要调用它时,你使用这个 completionHandler 参数(如果需要,可以在尾随闭包中):

Then, when you want to call it, you use this completionHandler parameter (in trailing closure, if you want):

let api = API()
api.getOrders() { responseObject, error in
    // use responseObject and error here

    print("responseObject = \(responseObject); error = \(error)")
    return
}

// but don't try to use them here

这篇关于如何从Alamofire返回价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆