Infaz Infaz - 1 month ago 15
JSON Question

AFNetworking issue with response : unauthorized (401)

I have used AFNetworking in my project, whenever i sent request,Im getting this message in failure block,


Error Domain=com.alamofire.error.serialization.response Code=-1011
"Request failed: unauthorized (401)"
UserInfo={com.alamofire.serialization.response.error.response=
com.alamofire.serialization.response.error.data=<7b227375 63636573
73223a66 616c7365 2c226d65 73736167 65223a22 41757468 656e7469
63617469 6f6e2066 61696c65 64227d>, NSLocalizedDescription=Request
failed: unauthorized (401)}


This is how I'm sending request by using AFNetworking.

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL]];

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];

NSString *path = [NSString stringWithFormat:@"/api/##/##/##/sign_in"];

NSString *params = @"{\"user\": {\"uid\": \"10236412002551\",\"access_token\":\"g6tdbvc34seadcx7yufbbcgvf8ijhss\",\"email\": \"user@domain1.com\",\"latitude\": \"6.927079\", \"longitude\": \"79.861243\",\"remote_avatar_url\": \"\"}}";

manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

AFSecurityPolicy* policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
[policy setValidatesDomainName:NO];
[policy setAllowInvalidCertificates:YES];

[manager POST:path parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
if([[responseObject objectForKey:@"error_code"] intValue]==0){
if (success) {
success(userArray);
}
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
if (failure) {
failure(error);
}
}];
}


But If I will be able to get the correct response by using NSURLSession.(Please refer below code)

NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

NSURL * url = [NSURL URLWithString:@"http://##/api/##/##/##/sign_in"];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];

NSString * params =@"{\"user\": {\"uid\": \"10236412002551\",\"access_token\":\"g6tdbvc34seadcx7yufbbcgvf8ijhss\",\"email\": \"user@domain1.com\",\"latitude\": 6.927079, \"longitude\": 79.861243,\"remote_avatar_url\": \"\"}}";

[urlRequest addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"Response:%@ %@\n", response, error);
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];

NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

NSLog(@"Data = %@",text);
NSLog(@"Data = %@",json);
}

}];
[dataTask resume];


I'm interested in using AFNetworking,But due to this issue I won't be able to move forward. Please help me to correct the issue with AFNetworking.

This is the request I should send,

{
"user": {
"uid": "102364120025511",
"access_token": "g6tdbvc34seadcx7yufbbcgaavf8ijh",
"email": "user@domain.com",
"latitude": 6.927079,
"longitude": 79.861243,
"remote_avatar_url": ""
}
}


This is the response I should get,

{
"success": true,
"message": "Successfully authenticated",
"user": {
"id": 123,
"email": "user@domain.com",
"provider": "facebook",
"latitude": 6.927079,
"longitude": 79.861243,
"avatar": {
"url": "",
"thumb": ""
}
}
}

Rob Rob
Answer

You're providing your params as a JSON string and then instructing AFNetworking to use a AFJSONRequestSerializer to then represent that string in a JSON structure. The net effect is that you've JSONified this twice.

You should provide dictionary object and let AFNetworking create the JSON for you, e.g.:

NSString *params = @{@"user": @{@"uid": @"10236412002551", @"access_token": @"g6tdbvc34seadcx7yufbbcgvf8ijhss", @"email": @"user@domain1.com", @"latitude": @6.927079, @"longitude": @79.861243, @"remote_avatar_url": @""}};

By the way, letting AFNetworking (which uses NSJSONSerialization) build the JSON for you will be far more robust than your trying to do this yourself. So, even if you use the NSURLSession approach, I'd suggest building this nested dictionary structure and then using NSJSONSerialization to build the JSON data payload. Or, if you use AFNetworking, it will do this for you.