user1007522 user1007522 - 2 months ago 15
iOS Question

JSON error in AFNetworking

I'm trying to use the AFNetworking library to send a post request to an URL like this:

https://m.com/api/2.0/basic/sim_balance.json

That expects a username and password in the URL that are my parameters (as NSDictionary).

The URL gives a JSON back like this:

{
"valid_until": "2011-05-05 22:13:28",
"sms": 0,
"sms_super_on_net_max": 300,
"voice_super_on_net": 0,
"credits": "0.00",
"bundles": [],
"is_expired": true,
"sms_super_on_net": 0,
"voice_super_on_net_max": 3600,
"data": 0
}


This is my request function:

+(void) request:(NSString *)endpoint : (NSDictionary *) parameters
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:endpoint parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}


I always get this as error:

Error: 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.) UserInfo=0x904b7e0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}


I validated the JSON and the server is sending valid JSON.

Can someone help me out on this?

Answer

I found the solution thanks to ester. Also you need to set the basic auth headers right.

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"Tom" password:@"test"];
[manager GET:endpoint parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {       
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Response data: %@",operation.responseData);      
    NSLog(@"Response String: %@",operation.responseString);     
    NSLog(@"Error: %@", error);
}];
}