我有一个问题。我正在使用 alamofire 请求它的返回值。在 alamofire 中,我将返回的 json 转换为我的自定义类,它的工作很好。但是当我从 alamofire 主体中使用这个转换后的类时,它返回了 nil 值。 我在 alamofire 中放置了断点,在那里我转换了 json 值并附加到我的类(class),它具有值(value)并将它放到我的类(class)中。但在 body 之外它等于零。为什么?
func getZakazDetail(orderID:Int,tableView:UITableView,spinner:UIActivityIndicatorView){
if flag{
let zD=ZakazDetailTableViewController()
Alamofire.request(.GET, "myUrl")
.responseJSON { response in
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error calling GET on /todos/1")
print(response.result.error!)
return
}
if let value = response.result.value {
let product = JSON(value)
if product != nil{
for (_,subJson):(String, JSON) in product {
let p=ZakazDetail(id: subJson["id"].int!, tovar: subJson["tovar"].string!, count: subJson["count"].int!, orderid: subJson["orderid"].int!, cena: subJson["cena"].int!)
self.zakazDetail.append(p)
zD.detail.append(p)
}
}
}
}
spinner.stopAnimating()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
tableView.reloadData()
}
else{
let alert = UIAlertView(title: "Ошибка",message: "Нету интернета!",delegate: nil,cancelButtonTitle: "OK")
alert.show()
}
}
最佳答案
发生这种情况是因为 alamofire 异步加载数据,并且在您将任何内容附加到 zD.detail.append(p) 之前。 为程序添加一个完成处理程序以等待加载完成。
//here you call authenticateUser with a closure that prints responseObject
API().authenticateUser{ (responseObject, error) in
println(responseObject)
}
然后:
//authenticateUser receives your closure as a parameter
func authenticateUser(completionHandler: (responseObject: String?, error: NSError?) -> ()) {
//it passes your closure to makeAuthenticateUserCall
makeAuthenticateUserCall(completionHandler)
}
//makeAuthenticateUserCall receives your closure
func makeAuthenticateUserCall(completionHandler: (responseObject: String?,
error: NSError?) -> ()) {
Alamofire.request(.GET, loginUrlString)
.authenticate(user: "a", password: "b")
//here you pass a new closure to the responseString method
.responseString { request, response, responseString, responseError in
//in this closure body you call your completionHandler closure with the
//parameters passed by responseString and your code gets executed
//(that in your case just prints the responseObject)
completionHandler(responseObject: responseString as String!, error: responseError)
}
}
有关更多信息,请阅读文档:Swift Closures
关于swift - alamofire 获取请求返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37803300/