2

I'm converting zip code data to city and state using http://api.zippopotam.us. I'm able to pull out the country easily, but the "place name" (city) and "state abbreviation" are giving me problems. Here's the code:

var url = NSURL(string: "http://api.zippopotam.us/us/90210")

let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: {(data, response, error) -> Void in

let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

        var placeDictionary = jsonResult["places"]! as? NSArray

        println(placeDictionary) // this works

        var name: String? = jsonResult[0]!.valueForKey("place name") as? String

        println(name) // this doesn't. 

})

task.resume()

I'm getting an error:

Unexpectedly found nil while unwrapping an Optional value

1
  • 2
    Hint: You don't use placeDictionary at all ... Commented Apr 18, 2015 at 20:13

2 Answers 2

3

Look at the cleaned up JSON:

{
   "post code":"90210",
   "country":"United States",
   "country abbreviation":"US",
   "places":[
      {
         "place name":"Beverly Hills",
         "longitude":"-118.4065",
         "state":"California",
         "state abbreviation":"CA",
         "latitude":"34.0901"
      }
   ]
}

The array is not directly in the JSON; to get there, you have to access the places key.

You've done that with placeDictionary (which should really be placeArray). Since you've saved that array, you can access elements of it (which are dictionaries) and their respective dictionaries.

So, to get the first place name, you'd use this:

if let placeName: String = (placeDictionary[0] as! NSDictionary).valueForKey("place name") as? String {
    println(placeName)
}
Sign up to request clarification or add additional context in comments.

3 Comments

Adding to this. using placeDictionary[0] will only get the first place name. I guess there can be multiple place names (why woud you use an array otherwise) If you want to get all place names you will have to iterate over the array
@milo526 I assumed the OP would adjust it as needed or loop through; I just used the first name in the result because that's what was used in the question.
Thanks, guys! Sometimes you just need another set of ideas to point out stupid mistakes.
1

If you are using JSON a lot, SwiftyJSON is worth checking out. It simplifies dealing with JSON a lot, since apple has not given us a good JSON API.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.