16

Jul

Easiest way to download remote files for iOS

I updated and open-sourced a utility for downloading web-hosted files for iOS today. Using it is extremely easy and doesn't require any notifications or delegates. Only sexy block syntax.

First, you'll need to import it in your implementation file:

#import "RemoteDataManager.h"

Then you can:

NSString *location = @"http://tailsmagazines.files.wordpress.com/2009/04/kitten.jpg?w=320&h=480";

[[RemoteDataManager sharedManager] getDataAtLocation:location withCallback:^(BOOL waiting, NSData *data){
    if(waiting){ // if the data is not cached
        [loadingIndicator startAnimating];
    }
    // when the data is available
    else{
        [loadingIndicator stopAnimating];
        imageView.image = [UIImage imageWithData:data];
    }
}];

The key thing to acknowledge here is that the Callback block may get called twice. Once, if the data for the remote URL is not cached on disk. In which case it initiates a request to save that data. Twice once that data is available.

You can see how the example above animates a UIActivitityIndicatorView until the callback is fired the second time. Then it stops animating the UIActivitityIndicatorView and sets the image for the imageView.

Grab the code here on github.