Archive for January 2020

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.

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];

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