嗨,我遇到了从api
读取JSON的NSJSONSerialization的问题代码:
func json() {
let urlStr = "https://apis.daum.net/contents/movie?=\etc\(keyword)&output=json"
let urlStr2: String! = urlStr.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())
let url = NSURL(string: urlStr2)
let data = NSData(contentsOfURL: url!)
do {
let ret = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) as! NSDictionary
let channel = ret["channel"] as? NSDictionary
let item = channel!["item"] as! NSArray
for element in item {
let newMovie = Movie_var()
// etc
movieList.append(newMovie)
}
catch {
}
}
我收到此错误
let ret = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) as! NSDictionary
致命错误:在解包可选值时意外发现nil
我该如何解决?
答案 0 :(得分:0)
NSData的 contentsOfURL 初始化程序的返回类型是可选的NSData。
let data = NSData(contentsOfURL: url!) //This returns optional NSData
由于 contentsOfURL 初始化方法返回一个可选项,因此首先需要使用打开可选项(如果让),然后使用数据(如果它不是nil),如下所示。< / p>
if let data = NSData(contentsOfURL: url!) {
//Also it is advised to check for whether you can type cast it to NSDictionary using as?. If you use as! to force type cast and if the compiler isn't able to type cast it to NSDictionary it will give runtime error.
if let ret = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as? NSDictionary {
//Do whatever you want to do with the ret
}
}
但是在您的代码段中,您不会检查从 contentsOfURL 获得的数据是否为零。您强行解开数据,在这种特殊情况下,数据为零,因此解包失败并且在解包可选值时出现错误 - 意外发现nil 强>
希望这有帮助。