源代码如下:
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)")
我如何解决这个问题
答案 0 :(得分:7)
您希望在使用之前测试和解包任何Optional
。这包括像as?
这样的强制转型。如果可以避免使用强制解包或明确解包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)
}