源代码如下 let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) if let blogs = json["profile_image_url"] as? String { userImage = blogs//json["profile_image_url"] as! String print("USER IMAGE:\(userIma
源代码如下
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) if let blogs = json["profile_image_url"] as? String { userImage = blogs//json["profile_image_url"] as! String print("USER IMAGE:\(userImage)")
我是如何解决这个问题的
您希望在使用之前测试和解包任何Optional.这包括像?的演员表.如果你可以避免它,你不应该使用强制解包或显式解包的Optional(用!标记),因为它们会导致意外的运行时崩溃.import Foundation // create test data let testJson = ["profile_image_url": "http://some.site.com/"] var data: NSData? // convert to NSData as JSON do { data = try NSJSONSerialization.dataWithJSONObject(testJson, options: []) } catch let error as NSError { print(error) } // decode NSData do { // test and unwrap data if let data = data { let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) // test and unwrap cast to String if let userImage = json["profile_image_url"] as? String { print("USER IMAGE:\(userImage)") } } } catch let error as NSError { print(error) }