2017-02-04 92 views
1

嘗試使用alamofire解析示例JSON對象,並且使用http中的SwiftlyJSON解析數據時遇到了麻煩,無法將其解析爲我的產品模型。這真的很奇怪,我在for循環中運行了調試器,我迭代並執行「po self.productlist」,該值確實附加到數組中。但是,當我嘗試在循環外打印時,它不起作用,當我嘗試在調試器模式下執行「po self.productlist [0] [」product「]時也是如此。它在工作中的某一點真的很奇怪。正如你所看到的,我在imgur鏈接下面附加了2張圖片。無法解析數據JSON alamofire SwiftJSON

我也附加了我的控制器和模型,我不知道我做了什麼錯誤,或者可能有錯誤。任何幫助,將不勝感激。由於

控制器

import UIKit 
import Alamofire 
import SwiftyJSON 

class AddProductController: UITableViewController { 
    var productlist = [Product]() 


    override func viewDidLoad() { 
     super.viewDidLoad() 

     Alamofire.request("https://api.myjson.com/bins/1f1zop").responseJSON { response in 
      let jsondata = JSON(data: response.data!) 
      for index in 0..<jsondata["data"].count{ 

       self.productlist.append(Product(id: jsondata["data"][index]["id"].stringValue, product: jsondata["data"][index]["product"].stringValue, category: jsondata["data"][index]["category"].stringValue, price: jsondata["data"][index]["price"].doubleValue)) 
      } 
     } 
     print(self.productlist[0]["id"]) 

型號

import Foundation 

class Product { 
    var id:String 
    var product:String 
    var category: String 
    var price: Double 


    init(id:String, product:String, category:String, price:Double) { 
     self.id = id 
     self.product = product 
     self.category = category 
     self.price = price 
    }  
} 

Controller shown with Product List[1]

Debugger shown variable productlist was indeed append with value] 2

更新到vadian 謝謝,我明白了!

回答

0

沒有錯誤,這就是着名的異步陷阱

Alamofire請求異步工作,JSON返回print行。

只需將print行(以及處理數組的代碼)放入完成塊。

發生此錯誤,因爲您嘗試像字典一樣獲得id。使用屬性.id

順便說一句:請不要在斯威夫特

Alamofire.request("https://api.myjson.com/bins/1f1zop").responseJSON { response in 
     let jsondata = JSON(data: response.data!) 
     for product in jsondata["data"].array! { 
      self.productlist.append(Product(id: product["id"].stringValue, product: product["product"].stringValue, category: product["category"].stringValue, price: product["price"].doubleValue)) 
     } 
     print(self.productlist[0].id) // use the property, it's not a dictionary. 
    } 

注意使用基於指數的循環:如果JSON是從第三方服務加載的,你應該使用可選的綁定解析數據安全。

+0

啊我其實已經嘗試了for循環,就像你所做的一樣,但我無法得到它的工作,可能錯過了「.array!」 此外,感謝它現在能夠打印。但我的主要目標是從alamofire codeblock獲取數據,所以我可以將數據傳輸到其他地方,例如tableview數據源等。這是否意味着我只能在該代碼塊內進行限制?對不起,如果它聽起來有點noob,我是非常新的ios編程,任何工作或建議從這裏獲取這些數據。 – Leo

+0

異步思考。只需在塊內寫入要執行的代碼,例如將數組分配給數據源數組並重新加載表視圖。但考慮在主線程上分派影響UI的代碼。 – vadian