I’m trying to download some files using NSURLConnection:
- (void)startDownload {
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req addValue:@"Basic XXXXXXXXXXXXXX=" forHTTPHeaderField:@"Authorization"];
connection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response {
filepath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:save_name];
[[NSFileManager defaultManager] createFileAtPath:filepath contents:nil attributes:nil];
file = [[NSFileHandle fileHandleForUpdatingAtPath:filepath] retain];
[file seekToEndOfFile];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[file seekToEndOfFile];
[file writeData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection*)connection {
[file closeFile];
}
My files are quite big, so I have to save every piece I download to a disk, can’t store them in RAM. The question is, how can I handle multiple downloads?
I was thinking to start the next download after the previous one is finished in - (void)connectionDidFinishLoading:, but I guess it is not the best way to do it. Any suggestions?
If you want to use NSURLConnection I would recommend making your own download object that wraps the connection and deals with writing it to disk.
You would initialise your object with a filename to put the finished file in and the URL to get the file from, something like :
Each download object would deal with it’s own NSURLRequest and NSURLConnection, using pretty much the same code as in your question 🙂
When it’s finished it would tell your view controller that it’s downloaded (probably via a delegate method but a notification would work just as well). You can then tell from the delegate method which file has finished.
If you made your MyDownloadObject a subclass of NSOperation then you could use an NSOperationQueue to limit the concurrent downloads and monitor overall progress etc.
If you didn’t mind using a third party library then ASIHTTPRequest is a good choice but be warned, it’s not being developed anymore. I suspect that other people on stack overflow will recommend better, more up to date, libraries you could use instead.