2016-08-24 129 views
0

你好我在与NSJSONSerialization从空气污染指数JSON问题JSONObjectWithData错误:意外发现零而展开的可选值

代码:

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 

致命错误:意外发现零,同时展开一个可选值

如何修复它?

+0

检查数据是否为nil,下一次请正确格式化您的代码。 –

回答

0

返回类型contentsOfURL NSData的初始值设定项是可选的NSData。

let data = NSData(contentsOfURL: url!) //This returns optional NSData 

由于contentsOfURL初始化方法返回一个可选的,首先需要解开可选使用如果让,然后使用该数据,如果如下所示它是不为零。

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得到为零与否。您正在强制展开数据,在这种特殊情况下,数据为零,因此解包失败,并提示错误 - 意外发现为零,同时展开可选值

希望这会有所帮助。

+0

谢谢! :)我会尽力解决您的帮助! –

相关问题