Moritz Moritz - 4 months ago 49
Swift Question

Swift Function to parse JSON and return a array of dictionaries

I tried to write a function to parse a JSON. The return-value of the function is an array of dictionary. Unfortunately, I have the problem that the assignment

result = data as! [[String:AnyObject]]
does not work. the
print(data)
returns my JSON wonderful back but the
print(result)
only gives me a empty array back. surprising it is that the method
print(result)

runs first and then the method
print(data)
run. please help me!

here my code:

import Foundation
import Alamofire
import SwiftyJSON

func getPlayers() -> Array<Dictionary<String, AnyObject>> {

var result = [[String:AnyObject]]()

Alamofire.request(.GET, "http://example.com/api/v1/players", parameters: ["published": "false"])
.responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let response = JSON(responseData.result.value!)

if let data = response["data"].arrayObject {
print(data)
result = data as! [[String:AnyObject]]
}
}
}

print(result)

return result
}

Answer

Api calling work in async (in background) manner that's why you need to use swift closure instead of returning dictionary. Change your code like this

func getPlayers(completion: (Array<Dictionary<String, AnyObject>>) -> ()))  {

    var result = [[String:AnyObject]]()

    Alamofire.request(.GET, "http://example.com/api/v1/players", parameters: ["published": "false"])
        .responseJSON { (responseData) -> Void in
            if((responseData.result.value) != nil) {
                let response = JSON(responseData.result.value!)
                if let data = response["data"].arrayObject {
                    print(data)
                    result = data as! [[String:AnyObject]]
                }
            }
            completion(result)
     }
}

And call like this

self.getPlayers() { (result) -> () in
     print(result)
}