Last Updated: February 25, 2016
·
3.391K
· lukerhodes

Post JSON Body to API with Basic HTTP Authentication using Objective C and AFNetworking 2.0

Be sure to check out the different NSURLCredentialPersistence options - and never write a password in code.

NSString *URLString = @"http://example.com/path";
NSDictionary *parameters = @{ };

NSURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

operation.credential = [NSURLCredential credentialWithUser:@"username" password:@"password" persistence:NSURLCredentialPersistencePermanent];
operation.responseSerializer = [AFJSONResponseSerializer serializer];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

[[NSOperationQueue mainQueue] addOperation:operation];