SwiftyJSON - 解析问题
SwiftyJSON - issues with parsing
我尝试用 SwiftyJSON 解析 json。其中一个字段有 url 图像,我尝试将其保存为 NSData 但我面临崩溃和控制台错误。编译器创建对象时出现崩溃
编码如下
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)
}
Link 到 JSON 是 http://wirehead.ru/article.json and here is with highlight http://pastebin.com/AAEFjsQN
我得到的错误是
有什么建议吗?
["images"]["main"]
包含由 String
表示的 URL
要获取图像数据,请使用类似这样的东西
let imgURLString = element["images"]["main"].stringValue
if let url = NSURL(string:imgURLString) {
let img = NSData(contentsOfURL:url)
}
我尝试用 SwiftyJSON 解析 json。其中一个字段有 url 图像,我尝试将其保存为 NSData 但我面临崩溃和控制台错误。编译器创建对象时出现崩溃
编码如下
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)
}
Link 到 JSON 是 http://wirehead.ru/article.json and here is with highlight http://pastebin.com/AAEFjsQN
我得到的错误是
有什么建议吗?
["images"]["main"]
包含由 String
要获取图像数据,请使用类似这样的东西
let imgURLString = element["images"]["main"].stringValue
if let url = NSURL(string:imgURLString) {
let img = NSData(contentsOfURL:url)
}