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];
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
#ios
#basic
#post
#objective-c
#body
#afnetworking
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#