I want my application to return to the original API call. Here is a sample code:
func getDataFromServer()
{
guard let apiUrl = URL(string: endPoint) else {
return
}
getAccessTokenValue( completionHandler:{ accesstoken in
//if access token is valid continue to get data
//.......
let task = self.apiSession.dataTask(with: apiRequest, completionHandler: {
(data, response, error) in
//Manage response/data/error
})
task.resume()
})
}
func getAccessTokenValue(completionHandlerResult : @escaping (_ accesstoken : String) -> ())
{
var hasAccessTokenExpired = true
// do some calculation
//check if access token has expired
if hasAccessTokenExpired
{
self.renewAccessToken(completionHandler: { accessTokenValue in
completionHandlerResult(accessTokenValue)})
}
else{
completionHandlerResult( accessToken) //return the current access token
}
}
func static func renewAccessToken (completionHandler : @escaping (_ accessTokenValue:String) -> ()) //
{
//another API call to refresh Access Token
//.......
let task = self.apiSession.dataTask(with: apiRequest, completionHandler: {
(data, response, error) in
//Manage response/data/error
//read access token from response
completionHandler(accessToken)
})
task.resume()
}
The problem I am facing is when my access token is no longer valid, the API for refresh token is fired but by the time the data task in renewAccessToken is completed, my application has already executed the end of getAccessTokenValue and getDataFromServer. So the API which should have been executed after getting the refreshed access token (in getDataFromServer's completion handler for getAccessTokenValue), is no longer fired.
I am not able to figure out where I have gone wrong.