2015-10-14 76 views
0

我嘗試用SwiftyJSON解析json。其中一個字段有url圖像,我嘗試將它保存爲NSData,但我面臨崩潰和控制檯錯誤。當編譯器來創建對象SwiftyJSON - 解析問題

代碼崩潰出現了以下

var JSONStorage : [Article?]? 
var objects = [Article?]() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    let number = arc4random_uniform(1000) 
    let urlString = "http://wirehead.ru/article.json?\(number)" 

    if let url = NSURL(string: urlString) { 
     if let data = try? NSData(contentsOfURL: url, options: []) { 
      let json = JSON(data: data) 

      for element in json["article"].arrayValue { 

       let id = Int(element["id"].stringValue) 
       let title = element["title"].stringValue 
       let subtitle = element["subtitle"].stringValue 
       let body = element["body"].stringValue 
       let img = element["images"]["main"].rawValue 
       let obj:Article = Article(id: id!, title: title, subtitle: subtitle, body: body, mainImage: img as! NSData) 

       objects.append(obj) 
       print("We are inside if let") 

      } 

     } 
    } 

    print(objects) 

} 

鏈接到JSON是http://wirehead.ru/article.json這裏是亮點http://pastebin.com/AAEFjsQN

錯誤,我得到的是

enter image description here

有什麼建議嗎?

+0

IMG的網址是不是NSData的...它是字符串... –

回答

2

["images"]["main"]包含由String

表示要獲取的圖像數據,使用這樣的

let imgURLString = element["images"]["main"].stringValue 
if let url = NSURL(string:imgURLString) { 
    let img = NSData(contentsOfURL:url) 
} 
+0

你的權利。坦克很多! –