Adrian I.
Adrian I.

Reputation: 135

CompletionHandler for Alamofire

I'm trying to return the responseJSON

static func getAllPersons(completionhandler:@escaping (Any) -> ()){
    let URL = baseURL + "api/person"
    Alamofire.request(URL).responseJSON {
        response in
        completionhandler(response.result.value as Any)
    }
}

But if i try to store the responseJSON in "res" it won't work:

var res: Any = ""
PersonResource.getAllPersons{ (result) in
    res = result
}
print(res)

Best regards

Upvotes: 2

Views: 3130

Answers (2)

orxelm
orxelm

Reputation: 1144

response.result.value is Optional, so try to return Any?. But this is better approach:

static func getAllPersons(completionhandler:@escaping ([String: Any]?, Error?) -> ()){
    let URL = baseURL + "api/person"
    Alamofire.request(URL).responseJSON {
        response in
        if let json = response.result.value as? [String: Any] {
                completionhandler(json, nil)
        }
        else if let error = response.result.error as Error? {
                completionHandler(nil, error)
        }
    }
}

Upvotes: 2

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20379

var res: Any = ""
PersonResource.getAllPersons{ (result) in
    res = result
    print(res)
}

Put print statement inside it will print the result

Why ?

PersonResource.getAllPersons is an asynchronous call so print(res) gets executed even before completion block of PersonResource.getAllPersons executes and sets res

Upvotes: 1

Related Questions