Archive for 9th February 2013

Migrating ASIHTTPRequest to AFNetworking

After using the ASIHTTPRequest library for a long time (so sad that Ben Copsey decided to abandon it), I finally decided to give in and switch to AFNetworking by Mattt Thompson and Scott Raymond. It has taken some trial and error to get it working correctly, so here is what I have found so far.

Conversion #1: Simple call to a URL

For this conversion, I am just making a call to a web service URL. I don’t really care about the return value, I just care if the call went through or whether there was an error in communications with the web service.

The ASI code:

    NSString *urlString = [NSString stringWithFormat:@"http://myurl.com?id=%@", theID];
    NSURL *url = [NSURL URLWithString:urlString];
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    [request setCompletionBlock:^{
        NSLog(@"success");
    }];
 
    [request setFailedBlock:^{
        NSError *error = [request error];
        NSLog(@"error: %@", error.localizedDescription);
    }];
 
    [request startAsynchronous];

The AFNetworking code:

    NSString *urlString = [NSString stringWithFormat:@"http://myurl.com?id=%@", theID];
    NSURL *url = [NSURL URLWithString:urlString];
    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:url]];
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSLog(@"success");
     }
                              failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
        NSLog(@"error: %@", error.localizedDescription);
     }];
 
    [op start];

Yeah, admittedly this one was not very hard to convert. Stay tuned, other more complicated conversions are coming.

BTW, Happy Birthday to Jim J. Bullock, who excellently portrayed Prince Valium in Spaceballs.