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

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

I use SFHFKeychainUtils as a wrapped for accessing and storing secure data - in this case, the user's password.

NSString *username = userProvidedUsername;
NSString *password = [SFHFKeychainUtils getPasswordForUsername:username andServiceName:@"com.mydomain.myapp.credentials" error:nil];

NSDictionary *jsonRequestDictionary = @{ @"request" : @{ @"someParameter" : @"someValue" }  };


NSString *baseURLString = @"http://example.com/";
AFHTTPClient *httpClient = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:baseURLString]]; //This can be re-used within a class property
[httpClient setAuthorizationHeaderWithUsername:username password:password];
httpClient.parameterEncoding = AFJSONParameterEncoding;

NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"path/to/api" parameters:jsonRequestDictionary];
AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request];


[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
    id response = responseObject[@"response"];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

}];

[operation start];