The following code successfully connects to my Ruby on Rails API and returns JSON using AFNetworking. What do I need to do to edit this to pass in a username and password so my API can use HTTP Basic Authentication?
I’ve read their documentation, but I am new to both Objective-C and AFNetworking and it isn’t currently making sense.
NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:3000/tasks.json"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request
, NSHTTPURLResponse *response
, id JSON) {
self.tasks = [JSON objectForKey:@"results"];
[self.activityIndicatorView stopAnimating];
[self.tableView setHidden:NO];
[self.tableView reloadData];
NSLog(@"JSON");
} failure:^(NSURLRequest *request
, NSHTTPURLResponse *response
, NSError *error
, id JSON) {
NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
}];
[operation start];
Answer updated for AFNetworking 2.x
For AFNetworking 2.x:
In 2.x, they did away with AFHTTPClient, so you’ll need to extend AFHTTPRequestOperationManager with your own class. Then, you can call that class from other code. For example, here’s a sample class that extends the AFHTTPRequestOperationManager:
SBAPIManager.h:
SBAPIManager.m:
Then, in your code, you can call it like this:
For AFNetworking 1.x:
The best practice for this in AFNetworking is to extend the AFHTTPClient with your own class. Then, you can call that class from other code. For example, here’s a sample class that extends the AFHTTPClient:
SBAPIManager.h:
SBAPIManager.m:
Then, in your code, you can call it like this: