DmitrievichR DmitrievichR - 1 year ago 97
Swift Question

swift alamofire json parse

i dont understand why i cant get empty dictionary [:] ?
I think I'm doing all right

func getCurrency() -> [String: AnyObject] {
var dict = [String: AnyObject]()
Alamofire.request("",encoding: JSONEncoding.default).responseJSON {
response in
if let status = response.response?.statusCode {
case 200:
let json = response.result.value as? [String: AnyObject]
let rates = json!["rates"] as? [String:AnyObject]
for i in rates! {
dict[i.key] = i.value
print("error with response status: \(status)")
return dict

Answer Source

I think you meant to ask "why you're GETTING an empty dictionary".

this is because your function getCurrency returns the dictionary before the request returns response

Alamofire is returning data asynchronously via a completionHandler pattern, so you must do the same. You cannot just return the value immediately, but you instead want to use Void return type and instead use a completion handler closure pattern.

something like this:

func getCurrentcy(completionHandler: @escaping (NSDictionary?, NSError?) -> ()) {

    Alamofire.request("",encoding: JSONEncoding.default)
        .responseJSON { response in
            switch response.result {
            case .success(let value):
                completionHandler(value as? NSDictionary, nil)
            case .failure(let error):
                completionHandler(nil, error as NSError?)


getCurrentcy { (responseObject:NSDictionary?, error:NSError?) in
        print("responseObject = \(responseObject); error = \(error)")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download