Rob Basso Rob Basso - 4 months ago 12x
JSON Question

Swift JSON parsing

I am working on an iOS weather app and need some help getting some values with JSON. I am trying to pull the value of id in the weather object. I am getting a value of nil when I debug. Could someone please help me with the logic? Here is the JSON request and Swift code.

"description":"clear sky",
"base":"cmc stations",

Here is my Swift snippet:

let requestURL: NSURL = NSURL(string: "")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in

let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode

if (statusCode == 200) {
print("JSON Downloaded Sucessfully.")


let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

if let today = json["weather"] as? [[String: AnyObject]] {
//this is pulling 4 key value pairs
for weather in today {

let id = weather["id"] as? String




catch {
print("Error with Json: \(error)")




try this in your code:
let id = weather["id"]?.stringValue

instead of this:
let id = weather["id"] as? String

And see the magic!

Edit for explanation:
As this answer worked for you, let me tell you why it did.
The id is being sent as integer from the server side. When you do weather["id"] it returns object of type AnyObject?. When you do weather["id"] as? String the casting fails thus you were getting nil.