0

I am making a web api call. I make the call from my class by calling the post method in my helper class. So i would like to return response i receive in the helper class(alamofire response) to the class the request is completed.

MyClass

let responseDictionary:[String:Any] = WebAPIHelper.postMethodRequest(parameters: requestParameters, methodName: "/User/SendEmail")

WebServiceHelper:

 static func postMethodRequest(parameters:Parameters, methodName:String) -> [String:Any]
{
    let headers:HTTPHeaders = generateHeaders(methodType: "POST", methodName: methodName)

    var responseDictionary:[String: Any] = ["OperationStatus":"Success"]

   Alamofire.request("http:acaapi.idyas.net" + methodName, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON{ response in

        //This control comes to this block after a delay i.e., once the response is received.  

        responseDictionary = response.result.value as! [String: Any]

        print(responseDictionary)

    }

    return responseDictionary // This line of code does not wait for the response to be received. Hence the control goes to MyClass before the response is received.

}

I want the method to return the responseDictionary only after the response is received. Can this be achieved with the help of Dispatchqueue or any other way to achieve this?

EDIT: Duncan: Pl try to understand the issue here. I want to return the response to another class. It is not just about calling a function inside the alamofire response block. I couldnt place the 'return responseDictionary' code inside the block. But what i need is, i want to return the responseDictionary after i receive the response.

Mano
  • 670
  • 1
  • 9
  • 28
  • 1
    You can not return from function that is making Async call use `completionHandler` will solved your issue, there are lots of answer related to that. – Nirav D Dec 14 '16 at 12:53
  • Can u pl tel me how to use the completion handler to solve this issue – Mano Dec 14 '16 at 12:54
  • 1
    Check this answer of my http://stackoverflow.com/a/40947185/6433023 and add completionHandler as last parameter in your `postMethodRequest`. – Nirav D Dec 14 '16 at 12:56
  • The short answer is that you can't wait. You have to write your method to take a completion handler, and invoke the completion handler when the request is complete. See the answers to the duplicate question for examples. Also see the SO Documentation entry on closures. – Duncan C Dec 14 '16 at 13:05

0 Answers0