software-mariodiana
2/4/2019 - 8:52 PM

How to add an HTTP header field to AFNetworking (v2.4.1)

How to add an HTTP header field to AFNetworking (v2.4.1)

- (IBAction)sendGETRequest:(id)sender
{
    AFHTTPSessionManager* manager =
        [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://localhost:8080"]];
    
    AFHTTPRequestSerializer* requestSerializer = [AFHTTPRequestSerializer serializer];
    
    // Simulate the JWT.
    [requestSerializer setValue:@"Bearer abc123doremiabc123babyuandme" forHTTPHeaderField:@"Authorization"];
    
    AFHTTPResponseSerializer* responseSerializer = [AFHTTPResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    
    manager.requestSerializer = requestSerializer;
    manager.responseSerializer = responseSerializer;
    
    [manager GET:@"/someresource.txt"
      parameters:nil
         success:^(NSURLSessionDataTask *task, id responseObject) {
             NSString* text = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
             NSLog(@"Response: \n%@", text);
    }
         failure:^(NSURLSessionDataTask *task, NSError *error) {
             NSLog(@"%@", error);
    }];
}