源代码如下
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) }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。