2016-08-24 130 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

謝謝! :)我會盡力解決您的幫助! –

相關問題