Search code examples
swiftalamofire

swift alamofire json parse


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

func getCurrency() -> [String: AnyObject] {
    var dict = [String: AnyObject]()
    Alamofire.request("http://api.fixer.io/latest?base=USD",encoding: JSONEncoding.default).responseJSON {
        response in
        if let status = response.response?.statusCode {
            switch(status){
            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
                }
            default:
                print("error with response status: \(status)")
            }
        }
    }
    return dict
}

Solution

  • 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("http://api.fixer.io/latest?base=USD",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?)
                }
        }
    }
    

    then

    getCurrentcy { (responseObject:NSDictionary?, error:NSError?) in
            print("responseObject = \(responseObject); error = \(error)")
        }