Search code examples
iosobjective-cjsonheaderafnetworking-2

setting a request header for an authorization token in afnetworking


I want to add an authorization token to the header of a get request(within this request I want to get some JSON information from my server) here it is my code:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
//[manager.requestSerializer setAuthorizationHeaderFieldWithToken:token];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[manager.requestSerializer setValue:@"4959a0bc00a15e335fb6" forHTTPHeaderField:@"Authorization"];
[manager GET:@"http://domain.com/recipes.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
    NSError *e=nil;

    recipesarray = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&e];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

I got this error: 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=0x7f8098529760 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set., NSUnderlyingError=0x7f8098513790 "Request failed: unauthorized (401)"}

does anyone know the reason? thanks a lot


Solution

  • You don't need a AFJSONRequestSerializer you need a AFJSONResponseSerializer

    request => response

    and AFJSONResponseSerializer is the default responseSerializer so just don't change requestSerializer