今天须要用AFNetworking实现断点续传的功能,可是在进行了一番研究以后,发现AFNetworking虽然支持下载文件的暂停和继续,可是程序从新启动后再次下载没法进行续传。网上有说能够经过AFDownloadRequestOperation这个AFNetworking的扩展库来实现从新启动后的续传,可是通过本人测试,这个库在最新的AFNetworking上会报错,无奈之下,参考他的代码,本身实现了一个,在这里分享给你们。xcode
实现的代码以下:缓存
- - (unsigned long long)fileSizeForPath:(NSString *)path {
- signed long long fileSize = 0;
- NSFileManager *fileManager = [NSFileManager new];
- 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格式不受影响。服务器
感谢分享app