0

Hi I'm having a problem with NSJSONSerialization reading JSON from 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!)

     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 {
    }
}

And I am getting this error

let ret = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) as! NSDictionary

fatal error: unexpectedly found nil while unwrapping an Optional value

How do I fix it?

return true
  • 7,839
  • 2
  • 19
  • 35
H.jenny
  • 171
  • 1
  • 2
  • 11

1 Answers1

0

The return type of the contentsOfURL initializer of NSData is optional NSData.

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

Since contentsOfURL initializer method returns an optional, first you need to unwrap the optional using if let and then use the data if it is not nil as shown below.

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
    }
}

But in case of your code snippet you're not checking the whether data that you get from contentsOfURL is nil or not. You're forcefully unwrapping the data and in this particular case the data is nil so the unwrapping is failing and it is giving the error - unexpectedly found nil while unwrapping an Optional value.

Hope this helps.

iamyogish
  • 2,372
  • 2
  • 23
  • 40