In my application, 2-4 API calls to my server can happen simultaneously (asynchronously) in my NSURLSession API NSURLSession . To make API requests to my server, I must provide an authentication token in the HTTPHeaderField each NSURLRequest . The token is valid for one day, and if it becomes invalid after one day, I need to update the token.
I do this in the following code in my API class:
-(void)sendTask:(NSURLRequest*)request successCallback:(void (^)(NSDictionary*))success errorCallback:(void (^)(NSString*))errorCallback { NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { [self parseResponse:response data:data fromRequest:request successCallback:success errorCallback:^(NSString *error) {
This sendTask method runs with every API request that I make in the application, so I just realized that this is a bad way to do this. If 3 API requests are not executed due to the token being invalid (one day has passed), all three of these API requests will try to force the API call to update the authentication token.
Is there a way for me to, in case one of the API requests fails, update the authentication token only once, and then retry failed API calls?
EDIT
I edited the question title to indicate that I am working with NSURLSession
PROGRESS
So far, to prevent several failed API requests from trying to update the authentication token at the same time, I have NSArray for all failed requests and NSNumber that serves as a lock to make sure that the authentication token only tries to be updated once. I do this in the following code:
-(void)sendTask:(NSURLRequest*)request successCallback:(void (^)(NSDictionary*))success errorCallback:(void (^)(NSString*))errorCallback { NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { MyAPIInterface *__weak weakSelf = self; [self parseResponse:response data:data fromRequest:request successCallback:success errorCallback:^(NSString *error) { NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response; if (httpResp.statusCode == 401) { if ([error isEqualToString:@"invalid_credentials"]) { errorCallback(@"Invalid username and/or password"); } else if ([error isEqualToString:@"Unknown error"]) { errorCallback(error); } else { if (!weakSelf.alreadyRefreshingToken.boolValue) {
Am I right about this? One part I'm paranoid about is that I don't actually call success or error callback at specific points. Could this lead to problems?