AFNetworking: Handle error globally and repeat request

前端 未结 6 1657
温柔的废话
温柔的废话 2020-12-07 11:07

I have a use case that should be rather common but I can\'t find an easy way to handle it with AFNetworking:

Whenever the server returns a specific status code for <

6条回答
  •  长情又很酷
    2020-12-07 11:53

    I use an alternative means for doing this with AFNetworking 2.0.

    You can subclass dataTaskWithRequest:success:failure: and wrap the passed completion block with some error checking. For example, if you're working with OAuth, you could watch for a 401 error (expiry) and refresh your access token.

    - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)urlRequest completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))originalCompletionHandler{
    
        //create a completion block that wraps the original
        void (^authFailBlock)(NSURLResponse *response, id responseObject, NSError *error) = ^(NSURLResponse *response, id responseObject, NSError *error)
        {
            NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
            if([httpResponse statusCode] == 401){
                NSLog(@"401 auth error!");
                //since there was an error, call you refresh method and then redo the original task
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
    
                    //call your method for refreshing OAuth tokens.  This is an example:
                    [self refreshAccessToken:^(id responseObject) {
    
                        NSLog(@"response was %@", responseObject);
                        //store your new token
    
                        //now, queue up and execute the original task               
                        NSURLSessionDataTask *originalTask = [super dataTaskWithRequest:urlRequest completionHandler:originalCompletionHandler];
                        [originalTask resume];
                    }];                    
                });
            }else{
                NSLog(@"no auth error");
                originalCompletionHandler(response, responseObject, error);
            }
        };
    
        NSURLSessionDataTask *task = [super dataTaskWithRequest:urlRequest completionHandler:authFailBlock];
    
        return task;
    
    }
    

提交回复
热议问题