DeiForm
DeiForm

Reputation: 664

Swift json parsing array

Working code, which parse states into array, but I cannot return the array so I can use it for picker, when I return the array it is empty. How could I return it from the competitionHandler?

class func getStates() -> Array<String> {

// 1
let urlAsString = "http://api.webotvorba.sk/states"
let url = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
var pickerStates = Array<String>()

pickerStates.append("test")

//2
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
    if (error != nil) {
        print(error!.localizedDescription)
    }

    // 3
    let jsonResult = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

    // 4
    let states: NSArray = (jsonResult.objectForKey("states") as? NSArray)!

    for state in states {

        if let stateCode: String = (state["state_code"] as? String), let stateName: String = (state["state_name"]) as? String {
            pickerStates.append(stateName)
            print(stateName)
        }

    }

})
// 5
jsonQuery!.resume()

print(pickerStates)
return pickerStates

}

Upvotes: 0

Views: 76

Answers (1)

Orion
Orion

Reputation: 1276

You already have an NSDictionary. You can access all it's values by simply accessing the key via jsonResult.objectForKey("key_here"). You can then cast the key as a value as a dictionary or array again. e.g.

if let states: NSArray = jsonResult.objectForKey("states") as? NSArray {
    for state in states {
        if let stateCode: NSNumber = states.objectForKey("state_code") as? NSNumber,
            let stateName: NSString = states.objectForKey("state_name") as? NSString {
                println(stateCode)
                println(stateName)
        }
    }
}

Above code is untested so might not work.

Upvotes: 1

Related Questions