swift - JSONObjectWithData error : unexpectedly found nil while unwrapping an Optional value -


hi i'm having problem nsjsonserialization reading json api

code:

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!)       {           let ret = try nsjsonserialization.jsonobjectwithdata(data!, options: nsjsonreadingoptions(rawvalue: 0)) as! nsdictionary           let channel = ret["channel"] as? nsdictionary          let item = channel!["item"] as! nsarray           element in item {          let newmovie = movie_var()           // etc           movielist.append(newmovie)     }       catch {     } } 

and getting error

let ret = try nsjsonserialization.jsonobjectwithdata(data!, options: nsjsonreadingoptions(rawvalue: 0)) as! nsdictionary 

fatal error: unexpectedly found nil while unwrapping optional value

how fix it?

the return type of contentsofurl initializer of nsdata optional nsdata.

let data = nsdata(contentsofurl: url!) //this returns optional nsdata 

since contentsofurl initializer method returns optional, first need unwrap optional using if let , use data if not nil shown below.

if let data = nsdata(contentsofurl: url!) {     //also advised check whether can type cast nsdictionary using as?. if use as! force type cast , if compiler isn't able type cast nsdictionary give runtime error.     if let ret = try nsjsonserialization.jsonobjectwithdata(data, options: nsjsonreadingoptions(rawvalue: 0)) as? nsdictionary {       //do whatever want ret     } } 

but in case of code snippet you're not checking whether data contentsofurl nil or not. you're forcefully unwrapping data , in particular case data nil unwrapping failing , giving error - unexpectedly found nil while unwrapping optional value.

hope helps.


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -