0

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

}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the ideas I made it work. Could you tell me how can I return the array so I can use it for picker? I call that function to receive the array and then I want to use it for picker.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.