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];
Written by Luke Rhodes
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Http
Authors
Related Tags
#http
#iphone
#dev
#json
#authentication
#basic
#post
#objective-c
#body
#afnetworking
#ios
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#