Pallet Town: Intro to AFHTTPClient Part 1

Pallet TownWelcome to Pallet Town! Pallet town is going to be an ongoing bi-weekly look at various development technologies and techniques from the perspective of someone new to that technology. For those who might know or (God forbid) are too young to get the reference, Pallet Town is the first town in the original Pokemon games for the Nintendo Gameboy.

This week we are going to take a look at getting some simple networking done with the new hotness in iOS networking frameworks: AFNetworking. To be specific we are going to focus on one of its more important classes: AFHTTPClient Now there are is a little bit of a prerequisite here, we are going to go ahead and assume that you have already added AFNetworking to your iOS project and we are also going to assume that we are going to use ARC.

For starters, let’s take a look at how we instantiate the AFHTTPClient:

Now that we have our client, let’s say we want to make a simple RESTFul GET call; this sample builds a bit on our Pokemon themed ASP.Net MVC web app from the last installment of Pallet Town. Ideally, this call would just get all the Pokemon available on the API; this of course assumes you followed the normal MVC patterns in your routing on the API. Here’s the code:

- (void)getAllPokemon
{ 
	AFHTTPClient* client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"SOME_URL_STRING"]];
	[client getPath:@"api/pokemon/" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
			NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
			NSLog(@"Request Successful, response '%@'", responseStr);
		} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
				NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
	}];
}

That was fun but let’s make things a little more complicated. Let’s say you want to pull a particular Pokemon via its Id. That’s still a GET request but takes a parameter like so:

- (void)getPokemonById:(NSNumber *)pokemonId
{ 
	NSDictionary* parameters = @{@"Id" : pokemonId}
	AFHTTPClient* client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"SOME_URL_STRING"]];
	[client getPath:@"api/pokemon/" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
			NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
			NSLog(@"Request Successful, response '%@'", responseStr);
		} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
				NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
	}];
}

Getting Pokemon from the server is a lot of fun, but you know in the age of Minecraft, I like to  be a little more creative than just working with the set number of Pokemon that Nintendo provides. Tune in for our next installment to see how to POST my very own legendary Pokemon to the server!