Restart failed NSURLSessionTask

I was wondering if it is possible to re-run the failed NSURLSessionDataTask. Here is the context in which I am facing this problem.

I have a web service object that uses AFNetworking 2.0 to process requests. In one of my methods, I have this:

[HTTPSessionManager GET:path parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {

} failure:^(NSURLSessionDataTask *task, NSError *error) {
    //sometimes we fail here due to a 401 and have to re-authenticate.
}];

Now sometimes the GET request fails because the user authentication token is in my backend. So what I would like to do is run a re-authentication block to find out if we can log in again. Something like that:

[HTTPSessionManager GET:path parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {

} failure:^(NSURLSessionDataTask *task, NSError *error) {
    if (task.response.statusCode == 401)
       RunReAuthenticationBlockWithSuccess:^(BOOL success) {
           //somehow re-run 'task'
        } failure:^{}
}];

Is there a way to run the task again?

Thanks!

+4
source share
1 answer

- , , HTTPSessionManager :

typedef void(^AuthenticationCallback)(NSString *updatedAuthToken, NSError *error);
typedef void(^AuthenticationBlock)(AuthenticationCallback);


@interface MYHTTPSessionManager : AFHTTPSessionManager
@property (nonatomic, copy) AuthenticationBlock authenticationBlock;
@end

@implementation MYHTTPSessionManager


- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler {

void (^callback)(NSString *, NSError *) = ^(NSString *tokenString, NSError *error) {
    if (tokenString) {
        //ugh...the request here needs to be re-serialized. Can't think of another way to do this
        NSMutableURLRequest *mutableRequest = [request mutableCopy];
        [mutableRequest addValue:AuthorizationHeaderValueWithTokenString(tokenString) forHTTPHeaderField:@"Authorization"];
        NSURLSessionDataTask *task = [super dataTaskWithRequest:[mutableRequest copy] completionHandler:completionHandler];
        [task resume];
    } else {
        completionHandler(nil, nil, error);
    }
};

void (^reauthCompletion)(NSURLResponse *, id, NSError *) = ^(NSURLResponse *response, id responseObject, NSError *error){

    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    NSInteger unauthenticated = 401;
    if (httpResponse.statusCode == unauthenticated) {
        if (self.authenticationBlock != NULL) {
            self.authenticationBlock(callback); return;
        }
    }

    completionHandler(response, responseObject, error);
};

return [super dataTaskWithRequest:request completionHandler:reauthCompletion];
}

@end
+3

Source: https://habr.com/ru/post/1525716/


All Articles