问题
I use NSURLConnection to download large files from the web on iPhone. I use the "didReceiveData" method to append data to a file in the Documents folder. It works fine.
If the download is interrupted (for instance, because the user pressed the "home" button), I would like to be able to continue to download the next time the user launch my application, and not from scratch!
Anyone can help me ?
回答1:
ASIHTTPRequest has easy to use support for resuming downloads:
http://allseeing-i.com/ASIHTTPRequest/How-to-use#resume
Alternatively, find out how much data you have downloaded already by looking at the size of the existing data, and set the 'Range' header on your NSMutableURLRequest:
[request addValue:@"bytes=x-" forHTTPHeaderField:@"Range"];
..where x is the size in bytes of the data you have already. This will download data starting from byte x. You can then append this data to your file as you receive it.
Note that the web server you are downloading from must support partial downloads for the resource you are trying to download - it sends the Accept-Ranges header if so. You can't generally resume downloads for dynamically generated content (e.g. a page generated by a script on the server).
回答2:
The only method I can think of is to break the file you're downloading up into smaller files. You can use the
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
method to determine when each portion of the file is finished, and restart the download at the last portion that didn't get downloaded.
回答3:
Look at the HTTP standard to see how you would form a request to start a transfer of a resource from a specific offset. I can't find any code offhand, sorry.
来源:https://stackoverflow.com/questions/975662/continue-an-interrupted-download-on-iphone