IPhone fault tolerant multi-file downloads

My application downloads image packages from the server. This is an array of direct links (20-50 files) from XML.

  • How can I fully download the entire set of images?

  • How to add a condition to cancel a full download (and delete all already downloaded files) if the application was closed with the iPhone button? (such methods are in AppDelegate, while all my download code is in some kind of downloadviewcontroller.m file)

  • Anything else I need to worry about when downloading multiple files? (5-10 MB total)

The code I use is not very safe in case of interruption of loading or closing the application. In the background thread, I call this method for each file:

(BOOL) loadImageFromURL:(NSString *)url withName:(NSString *)filename toFolder:(NSString *)folder { NSURL *link = [NSURL URLWithString:url]; NSFileManager *manager = [NSFileManager defaultManager]; NSString *filepath = [folder stringByAppendingPathComponent:filename]; if ([manager fileExistsAtPath:filepath]) { return YES; } else { UIImage *image = [[UIImage imageWithData:[NSData dataWithContentsOfURL:link]] retain]; NSData *data = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)]; if ([data length] <= 0) [image release]; return NO; // no data else { [data writeToFile:filepath atomically:YES]; [image release]; return YES; } } } 
+4
source share
2 answers

Use nsoperation for this

check link ..

http://www.cimgf.com/2008/02/16/cocoa-tutorial-nsoperation-and-nsoperationqueue/

now in August 2012 try to find wwdc 2012 video no 211 to find out nsoperation. You can use the block for this.

 [aNsque addExecutionBlock:^{ ...code... }]; 

where aNsque is nsblockoperation.

+2
source

Do not use a synchronous call to dataWithContentsOfURL . Instead, see how to use the asynchronous NSURLConnection method, - initWithRequest: delegate:

Then you can cancel the request using [connection cancel]; Also, you do not have to run it in another thread, because it is already asynchronous.

As for running multiple queries, you may have several options. One idea would be to create an abject that launches NSURLConnection and parses the response, and then creates an array of these objects.

+2
source

All Articles