Last Updated: February 25, 2016
·
3.058K
· 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];

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

Account takeover often starts in the browser, on the login page itself. A malicious script can read credentials, tokens, or one-time codes as the person types them.

Security insights from Cside