I try to create request in func and after call the func and return responсe json. But because request is async response arrived after func returns any data.
How handle request finishing?
I try to create request in func and after call the func and return responсe json. But because request is async response arrived after func returns any data.
How handle request finishing?
Pass a closure to your function, and call that closure with the result of the URL request.
You have asked for code so I am giving you some code snippets. Please modify it as per your requirement. These codes are using Alamofire but mainly you need to know how to handle response in callback.
func requestYourApi(_ requestParams:[String:AnyObject], callback:@escaping (Dictionary<String, Any>, Error?)-> Void)
{
let parameters:Parameters = requestParams
Alamofire.request("https:yourUrl", method: .post, parameters: parameters, encoding: JSONEncoding.prettyPrinted).responseJSON { response in
debugPrint("response: \(response)")
switch response.result
{
case .success(let value):
callback(value as! Dictionary, nil)
case .failure(let error):
callback([:], error)
}
}
}
And call the above method like this, wherever required. You'll get the response in responseObj
and error in error
.
requestYourApi(requestParams as [String : AnyObject]) { (responseObj, error) in
DispatchQueue.main.async
{
if responseObj.count != 0
{
// Do something with your response
}
}
}