How to get status code in AFNetworking
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;
}
}
Comments
-
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 over 10 yearsI 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 over 10 yearsInstead 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 over 10 yearsI didn't put -1 to you. I have only 13 reputation, I can't even vote. I can only select best answer now
-
Dimentar over 10 yearsMy apologize. Someone else - very smart
-
abekenza over 10 yearsThanks, 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 about 10 yearsNSInteger should be used going forward as we move to 64 bit arch.
-
Ryan Romanchuk about 10 yearsThis is not valid for
AFURLSessionManager
which uses tasks, notAFHTTPRequestOperation