iOS 大檔案斷點下載,iOS檔案斷點下載
iOS 在下載大檔案的時候,可能會因為網路或者人為等原因,使得下載中斷,那麼如何能夠進行斷點下載呢?
// resumeData的檔案路徑#define XMGResumeDataFile [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"resumeData.tmp"]#import "ViewController.h"@interface ViewController () <NSURLSessionDownloadDelegate>/** 下載任務 */@property (nonatomic, strong) NSURLSessionDownloadTask *task;/** 儲存上次的下載資訊 */@property (nonatomic, strong) NSData *resumeData;/** session */@property (nonatomic, strong) NSURLSession *session;@end
@implementation ViewController/** session */- (NSURLSession *)session{ if (!_session) { _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; } return _session;}/** * 開始下載 */- (IBAction)start:(id)sender { self.task = [self.session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]]; [self.task resume];}/** * 暫停下載 */- (IBAction)pause:(id)sender { // 一旦這個task被取消了,就無法再恢複 [self.task cancelByProducingResumeData:^(NSData *resumeData) { self.resumeData = resumeData; }];}/** * 繼續下載 */- (IBAction)goOn:(id)sender { self.task = [self.session downloadTaskWithResumeData:self.resumeData]; [self.task resume];}#pragma mark - <NSURLSessionDownloadDelegate>- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{ NSLog(@"didCompleteWithError"); // 儲存恢複資料 self.resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];}- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{ NSLog(@"didResumeAtOffset");}/** * 每當寫入資料到臨時檔案時,就會調用一次這個方法 * totalBytesExpectedToWrite:總大小 * totalBytesWritten: 已經寫入的大小 * bytesWritten: 這次寫入多少 */- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{ NSLog(@"--------%f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite);}/** * * 下載完畢就會調用一次這個方法 */- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{ // 檔案將來存放的真實路徑 NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; // 剪下location的臨時檔案到真實路徑 NSFileManager *mgr = [NSFileManager defaultManager]; [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];}@end