Q:

stop NSData loading from server

I have the following method, which basically loads an array of image data into an array:
-(void)loadImages:(NSMutableArray*)imagesURLS{
    //_indexOfLastImageLoaded = 0;
    [_loadedImages removeAllObjects];
    _loadedImages = [[NSMutableArray alloc]init];;
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        for (int i=0; i<imagesURLS.count;i++){
            NSLog(@"loading image for main image holder at index %i",i);
            NSData *imgData = [NSData dataWithContentsOfURL:[imagesURLS objectAtIndex:i]];
            UIImage *img = [UIImage imageWithData:imgData];
            [_loadedImages addObject:img];
            //_indexOfLastImageLoaded++;
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"_loadedImages download COMPLETE");                      
        });
    });

}

I want to be able to stop it when, for example, a user moves away from the view controller that these images are being loaded in. What is the best way to do so?
Thanks!

A:

You can't cancel NSData dataWithContentsOfUrl:. The best way to achieve cancelable, asynchronous downloading is by using NSURLConnection and the NSURLConnectionDataDelegate. 
You set up an NSMutableData object to accumulate all the data as it comes in in chunks. Then when all the data has arrived, you create your image and use it.
.h
@interface ImageDownloader : NSObject <NSURLConnectionDataDelegate>
@property (strong, nonatomic) NSURLConnection *theConnection;
@property (strong, nonatomic) NSMutableData *buffer;
@end

.m
-(void)startDownload
{
    NSURL *imageURL = [NSURL URLWithString: @"http://example.com/largeImage.jpg"];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL: imageURL];
    _theConnection = [[NSURLConnection alloc] initWithRequest: theRequest delegate: self startImmediately: YES];
}

-(void)cancelDownload
{
    // CANCELS DOWNLOAD
    // THROW AWAY DATA
    [self.theConnection cancel];
    self.buffer = nil;
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // INITIALIZE THE DOWNLOAD BUFFER
    _buffer = [NSMutableData data];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // APPEND DATA TO BUFFER
    [self.buffer appendData: data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
     // DONE DOWNLOADING
    // CREATE IMAGE WITH DATA
    UIImage *theImage = [UIImage imageWithData: self.buffer];
}

