AFNetworking实现程序重新启动时的断点续传
用AFNetworking实现断点续传的功能,研究后,发现AFNetworking虽然支持下载文件的暂停和继续, 但是程序重新启动后再次下载无法进行续传。网上有说可以通过AFDownloadRequestOperation这个AFNetworking的扩展库 来实现重新启动后的续传,但是经过本人测试,这个库在最新的AFNetworking上会报错,无奈之下,参考他的代码,自己实现了一个,在这里分享给大 家。
实现的代码如下:
//获取已下载的文件大小 - (unsigned long long)fileSizeForPath:(NSString *)path { signed long long fileSize = 0; NSFileManager *fileManager = [NSFileManager new]; // default is not thread safe if ([fileManager fileExistsAtPath:path]) { NSError *error = nil; NSDictionary *fileDict = [fileManager attributesOfItemAtPath:path error:&error]; if (!error && fileDict) { fileSize = [fileDict fileSize]; } } return fileSize; } //开始下载 - (void)startDownload { NSString *downloadUrl = @"http://www.xxx.com/xxx.zip"; NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *downloadPath = [cacheDirectory stringByAppendingPathComponent:@"xxx.zip"]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:downloadUrl]]; //检查文件是否已经下载了一部分 unsigned long long downloadedBytes = 0; if ([[NSFileManager defaultManager] fileExistsAtPath:downloadPath]) { //获取已下载的文件长度 downloadedBytes = [self fileSizeForPath:downloadPath]; if (downloadedBytes > 0) { NSMutableURLRequest *mutableURLRequest = [request mutableCopy]; NSString *requestRange = [NSString stringWithFormat:@"bytes=%llu-", downloadedBytes]; [mutableURLRequest setValue:requestRange forHTTPHeaderField:@"Range"]; request = mutableURLRequest; } } //不使用缓存,避免断点续传出现问题 [[NSURLCache sharedURLCache] removeCachedResponseForRequest:request]; //下载请求 AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; //下载路径 operation.outputStream = [NSOutputStream outputStreamToFileAtPath:downloadPath append:YES]; //下载进度回调 [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { //下载进度 float progress = ((float)totalBytesRead + downloadedBytes) / (totalBytesExpectedToRead + downloadedBytes); }]; //成功和失败回调 [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { } failure:^(AFHTTPRequestOperation *operation, NSError *error) { }]; [operation start]; }
需要注意的是,此种写法仅适用于下载zip包,因为下载其他格式的文件有可能出现数据过多的情况。当文件已经下载完成时,再次调用该函数,无法判断文件是 否已经下载完整,于是会再次下载,此时服务器会报416错,同时返回也会输出到文件中,使得文件大小异常。但是zip格式不受影响。
转载自 http://blog.csdn.net/zhaoxy_thu/article/details/21383515