AFNetworking
If you’re an iOS dev, you must have somehow came across this amazing and widely used framework called AFNetworking. And easy way to explain what AFNetworking is that it’s an alternative framework for devs to use when uploading and downloading data. That’s probably an easy-lay-man term way to explain it. If you would like to know more about what is AFNetworking, feel free to google it, it’s so popular, you wouldn’t miss it.
Anyway, AFNetworking framework isn’t exactly new. It’s been around for quite abit, not super long, but it’s not new either. It’s currently in version 2 already. Shameful to admit, but I was still sticking to the good old NSURLConnection when it comes to dealing with API data. Of course there is nothing wrong with it, it’s just....old. AND THOUSANDS OF LINES OF CODE TO GET THINGS DONE. So why do I still use it? I guess it’s because I’ve been using it for tons of time and it just became a habit.
I decided to kick that “habit” out, and try to play around with AFNetworking framework. There’s lots that you can do with it, but for this post, I’ll be covering what most dev would be using it for, which is to download API responses to their app.
It’s always a little daunting to try out new things, especially when you’re so use to things that you’ve been doing for tons of time. But after using AFNetworking, BA-BAM! What you can do with NSURLConnection, is achievable with lesser and cleaner code with AFNetworking.
Here’s the 5 simple general steps in using this cool framework to download API response:
1. Get the API URL
2. Initialize AFHTTPRequestOperation
3. Specify how do you want your data to be serialized - XML, JSON, Property List
4. Retrieve the data with setCompletionBlockWithSuccess - has failure and success
5. DON'T FORGET TO CALL START!!
Sample code is as below:
//1 NSString *weatherURLString = [NSString stringWithFormat:@"Your url string here"]; NSURL *weatherURL = [NSURL URLWithString:weatherURLString]; NSURLRequest *request = [NSURLRequest requestWithURL:weatherURL];
//2 AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//3 operation.responseSerializer = [AFJSONResponseSerializer serializer];
//4 [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//success NSLog(@"Response Object %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure. [self alertNotification:@"Download is dead simple"];
}];
//5 [operation start];
Clean. For those who are considering of using AFNetworking framework, give it a shot. =]
















