AFNetworking: Handle error globally and repeat request

前端 未结 6 1658
温柔的废话
温柔的废话 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 12:02

    In the AFHTTPClient's init method register for the AFNetworkingOperationDidFinishNotification which will be posted after a request finishes.

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(HTTPOperationDidFinish:) name:AFNetworkingOperationDidFinishNotification object:nil];
    

    In the notification handler check the status code and copy the AFHTTPRequestOperation or create a new one.

    - (void)HTTPOperationDidFinish:(NSNotification *)notification {
      AFHTTPRequestOperation *operation = (AFHTTPRequestOperation *)[notification object];
    
        if (![operation isKindOfClass:[AFHTTPRequestOperation class]]) {
            return;
        }
    
        if ([operation.response statusCode] == 401) {
            // enqueue a new request operation here
        }
    }
    

    EDIT:

    In general you should not need to do that and just handle the authentication with this AFNetworking method:

    - (void)setAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block;
    

提交回复
热议问题