Migrating AFNetworking to NSURLSession

I have some legacy Objective-C code that I want to bring up to the latest iOS code. Part of this is migrating AFNetworking to NSURLSession.

Not that I have anything against AFNetworking of course, I have used it for a very long time, especially when the communications capabilities in the Foundation framework were a bit more primitive than they are now. I have just been trying to reduce dependencies in my projects where I can, and for my communications needs, the newer Foundation classes give me the same kind of ease of use that AFNetworking has.

For example, here is a simple example of some of the legacy code that I have in the app:

NSURL *url = [NSURL URLWithString:@"http://link.to.the.site.you.are.loading"];    
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:url]];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    // do something with the operation.responseString
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // an error occurred
}];    
[op start];

And here is what it looks like when you migrate to NSURLSessionDataTask:

NSURL *url = [NSURL URLWithString:@"http://link.to.the.site.you.are.loading"];
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (error != nil)
        {
            // an error occurred
        }
        else
        {
            // do something with the data
        }
    });
}];
[task resume];

All in all, I think that 7 years of usage (I migrated to AFNetworking in 2013 as described in the post Migrating ASIHTTPRequest to AFNetworking) is pretty good for using a library. Kudos to the team maintaining that library, I do not know if I would have the patience to stick with it for that long.

BTW, Happy Birthday to John Myung, bass player for Dream Theater.

Leave a Reply