Search code examples
iosswiftalamofirecompletionhandler

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


Solution

  • 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