Justin
Justin

Reputation: 2999

Download mutiple files in background thread

I am making an iPad app where you can download files (like PDF, doc, etc) and view them offline.

I already have the view part and you can download a file to the document directory. As it is now you need to wait for the download to be finished to move on. This can be solved by putting it in a thread, but what happens when the user downloads multiple files or even download the same file multiple times?

My idea is to make a download queue, with a view for the progress.

Workflow:

I want to make a threaded download class where you can add urls to be downloaded. the class has methods to cancel and delete document-downloads, but also has methods to return the progress. If possible the class can handle simultaneous downloads.

The problem is, I don't know where to start?

Upvotes: 1

Views: 4407

Answers (2)

steipete
steipete

Reputation: 7641

I've written an open source example that has pretty much all features you want, canceling a download is currently only available in code, but it's pretty easy to add a button for that.

I'm using asi-http-request for managing the downloads, and they are displayed in a grid view (AQGridView) instead of a UITableView, but i think you get the idea.

Download progress is managed via KVO.

See PSPDFDownload.m for a start. Download the full demo here

Full disclosure: This demo uses PSPDFKit for faster pdf display. But the Kiosk example is exactly what you need, and you don't need to use PSPDFKit for pdf display. There's even an example code path that uses Apple's QuickLook.

Upvotes: 0

August Lilleaas
August Lilleaas

Reputation: 54603

NSURLConnection is already asynchronous. All you need to do is to create NSURLConnection instances, associate them with your data structures, and have at it.

Here's an example where I assume you have one UIView per item. If you use a table view you can't count on view instances, but instead associate a download with an NSIndexPath, or something else.

@implementation MyDownloadView
- (void)startDownload {
    NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
    [req setHTTPMethod:@"GET"];
    // Set headers etc. if you need
    [[[NSURLConnection alloc] initWithRequest:req delegate:self] autorelease];
    [req release];

    self.responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Alternatively, store to a file so you don't run out of memory
    [self.responseData appendData:data];
}
@end

Then implement the other NSURLConnection delegate methods to do what you need.

Upvotes: 3

Related Questions