alamofire get请求返回null值

时间:2016-06-14 05:00:40

标签: swift alamofire

我有一个问题。我正在用alamofire回报它的回报价值。在alamofire我将返回的json转换为我的自定义类,它的工作goog。但是当我在alamofire身体中使用这个转换后的类时,它返回了nil值。 我把断点放在alamofire中,在那里我转换了json值并且加入了我的班级,它有价值并且把它放到了我的班级。但是它在身体之外它等于零。为什么呢?

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

}

1 个答案:

答案 0 :(得分:0)

这种情况正在发生,因为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