How to get status code in AFNetworking

22,643

Solution 1

Finally found answer, may be it will be helpful for someone. I just needed to use:

NSInteger statusCode = operation.response.statusCode;

And i can catch it like:

    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"response:%@", responseObject);
        [self parseResponseForUser:responseObject];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSInteger statusCode = operation.response.statusCode;
        if(statusCode == 401) {
        } else if (statusCode == 404) {
        }
    }];

Solution 2

In AFNetworking 3.0+ and in the case of an error, you can access the status code in the failure block's error.userInfo object:

failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];

    NSInteger statusCode = response.statusCode;

    // Do something with the status code
}];

Solution 3

you can give a try to get code from error and then show messages accordingly.

failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSInteger statusCode = error.code;
    if(statusCode == -1001) {
      // request timed out
    } else if (statusCode == -1009 || statusCode || -1004) {
      // no internet connectivity
    }
}];

similarly you can check for other code.

Solution 4

Here's how I do it.

[self.httpClient GET:@"someAPI"
          parameters:parametersDictionary
             success:^(NSURLSessionDataTask *task, id responseObject) {
             } failure:^(NSURLSessionDataTask *task, NSError *error) {
               NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
               NSInteger statusCode = [response statusCode];
               switch (statusCode) {
                 case 404:
                   break;
                 default:
                   break;
               }
             }];

Solution 5

Here is how to do it in Swift

((NSURLSessionDataTask, NSError) -> Void) = { (sessionDataTask :NSURLSessionDataTask, responseError : NSError) -> Void in
    let response  = sessionDataTask.response as! NSHTTPURLResponse
    switch (statusCode) {
      case 404:
        // do stuff
      case 401:
        // do stuff
      default:
        break;
    }
}
Share:
22,643
abekenza
Author by

abekenza

Software Engineer: iOS, Android, Java, JavaEE, MySQL

Updated on July 09, 2022

Comments

  • abekenza
    abekenza almost 2 years

    I have a method, for authorizing user. I need Basic authorization.

        NSString *url = [NSString stringWithFormat:@"%@/rest/api/person/auth", host];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
        [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:_loginField.text password:_passwordField.text];
        [manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
        [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [self parseResponseForUser:responseObject];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error %@ ",error);
        }];
    

    The main problem here is determining error type. I may have error for authorization and error for network connection problem (host is not reachable). When login and password don't match criteria, failure block runs. For example, If I put wrong password and login I take this error message.:

    Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.)

    How should i catch error types?

  • abekenza
    abekenza over 10 years
    I am sure that JSON is right, because I can parse the data, when I enter correct login and password. The problem occurs when I enter incorrect login or password. The server side sends me html response (error 401, user is not authorized) instead of json. I would like to catch errors, so that if error type is equal to 401, I want to show an alertview like "User is not authorized", if error type equals 404, i want to show user "incorrect url message". Any help would be appreciated.
  • Dimentar
    Dimentar over 10 years
    Instead putting -1 write your question correctly. And the answer is: first of [self parseResponseForUser:responseObject]; check your responceObject content and type, and if(is 404 ?) {alert} else {[self parseResponseForUser:responseObject];}
  • abekenza
    abekenza over 10 years
    I didn't put -1 to you. I have only 13 reputation, I can't even vote. I can only select best answer now
  • Dimentar
    Dimentar over 10 years
    My apologize. Someone else - very smart
  • abekenza
    abekenza over 10 years
    Thanks, AAron. Today I tried this solution, but i get stucked, from where I should import AFCompoundSerializer. Reading documentation of AFNetworking I found method for getting statusCode.
  • ryanconnellyatl
    ryanconnellyatl about 10 years
    NSInteger should be used going forward as we move to 64 bit arch.
  • Ryan Romanchuk
    Ryan Romanchuk about 10 years
    This is not valid for AFURLSessionManager which uses tasks, not AFHTTPRequestOperation