2015-10-14 72 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

你的权利。坦克很多! –