2016-06-14 142 views
1

我有一個問題。我正在用alamofire回報它的回報價值。在alamofire我將返回的json轉換爲我的自定義類,它的工作goog。但是當我將這個轉換後的類從alamofire body中取出時,它返回了零值。 我在alamofire中放置了斷點,在那裏我轉換了json的值,並且向我的類中添加了它,它具有價值,並將它放到我的類中。但是超出正文它等於零。爲什麼?alamofire得到請求返回空值

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

} 

回答

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

+0

但也有它已經下載JSON讓產品= JSON(值) –

+0

呀很好,你應該告訴代碼在alamofire加載數據之前不會追加任何內容,然後一旦完成,您可以追加它並重新加載數據。 – Dershowitz123

+0

是這樣的: func getZakazDetail(orderID:Int,tableView:UITableView,spinner:UIActivityIndi​​catorView,completion:(JSON) - >())let product = JSON(value) 完成(產品) –