标签:
一 实现如下效果
二 实现代码
1 // 2 // ViewController.m 3 // AFNetworking实现断点下载 4 // 5 // Created by lovestarfish on 15/11/15. 6 // Copyright © 2015年 大爱海星星. All rights reserved. 7 // 8 #define kURL @"http://61.163.117.26/wvideo.spriteapp.cn/video/2015/0714/55a4be6ab563a_wpd.mp4?wsiphost=local" 9 #import "ViewController.h" 10 #import "AFNetworking.h" 11 12 @interface ViewController () 13 14 @property (weak, nonatomic) IBOutlet UILabel *progressLabel; 15 @property (weak, nonatomic) IBOutlet UIProgressView *progressView; 16 @property (nonatomic,strong) AFHTTPRequestOperation *operation; 17 18 - (IBAction)start:(UIButton *)sender; 19 20 @end 21 22 @implementation ViewController 23 24 - (void)viewDidLoad { 25 [super viewDidLoad]; 26 // 获取保存下载进度的缓存文件 27 NSString *txtTempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"mvTemp/mv.txt"]; 28 NSLog(@"%@",txtTempPath); 29 NSFileManager *fileManager = [NSFileManager defaultManager]; 30 // 判断文件夹里面有没有之前的缓存文件 31 if ([fileManager fileExistsAtPath:txtTempPath]) { 32 // 有的话继续之前的下载进度下载 33 self.progressView.progress = [[NSString stringWithContentsOfFile:txtTempPath encoding:NSUTF8StringEncoding error:nil] floatValue]; 34 } else { 35 // 没有的话进度从0开始 36 self.progressView.progress = 0; 37 } 38 39 // 设置显示进度的label内容 40 self.progressLabel.text = [NSString stringWithFormat:@"%.2f%%",self.progressView.progress * 100]; 41 42 NSLog(@"%@",NSHomeDirectory()); 43 } 44 45 /** 46 * 开始下载 47 */ 48 - (IBAction)start:(UIButton *)sender { 49 if ([sender.currentTitle isEqualToString:@"开始下载"]) { 50 // 如果已经开始下载,将按钮标题置为"暂停下载" 51 [sender setTitle:@"暂停下载" forState:UIControlStateNormal]; 52 // 下载的url 53 NSURL *url = [NSURL URLWithString:kURL]; 54 // 获取cache文件夹 55 NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; 56 NSFileManager *fileManager = [NSFileManager defaultManager]; 57 // 在cache文件夹创建mv文件夹,用来存放下载成功地资料 58 NSString *folderPath = [cachePath stringByAppendingPathComponent:@"mv"]; 59 // 在缓存文件夹里创建mvTemp文件夹用来临时存放下载信息 60 NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"mvTemp"]; 61 // 判断缓存文件夹和视频存放文件夹是否存在,如果不存在,就创建一个文件夹 62 if (![fileManager fileExistsAtPath:folderPath]) {// 如果不存在视频文件夹 63 [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil]; 64 } 65 if (![fileManager fileExistsAtPath:tempPath]) { // 如果不存在缓存文件夹 66 [fileManager createDirectoryAtPath:tempPath withIntermediateDirectories:YES attributes:nil error:nil]; 67 } 68 69 // 缓存路径(缓存当前下载的容量值) 70 NSString *tempFilePath = [tempPath stringByAppendingPathComponent:@"mv.temp"]; 71 72 // 保存重启程序下载的进度(保存当前下载的进度值) 73 NSString *txtFilePath = [tempPath stringByAppendingPathComponent:@"mv.txt"]; 74 75 // 文件保存路径 76 NSString *mvFilePath = [folderPath stringByAppendingPathComponent:@"mv.mp4"]; 77 78 // 初始化下载字节数为0 79 unsigned long long downloadedBytes = 0; 80 // 创建请求 81 NSURLRequest *request = [NSURLRequest requestWithURL:url]; 82 if ([fileManager fileExistsAtPath:tempFilePath]) {//如果存在,说明有缓存文件 83 // 计算缓存文件的大小 84 downloadedBytes = [self fileSizeAtPath:tempFilePath]; 85 NSLog(@"%llu",downloadedBytes); 86 // 创建可变请求 87 NSMutableURLRequest *mutableRequest = [request mutableCopy]; 88 NSString *requestRange = [NSString stringWithFormat:@"bytes=%llu-",downloadedBytes]; 89 90 [mutableRequest setValue:requestRange forHTTPHeaderField:@"Range"]; 91 request = mutableRequest; 92 NSLog(@"==============断点下载"); 93 } 94 95 if (![fileManager fileExistsAtPath:mvFilePath]) { 96 [[NSURLCache sharedURLCache] removeCachedResponseForRequest:request]; 97 self.operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 98 [self.operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:tempFilePath append:YES]]; 99 100 // 设置下载进度的block 101 __block ViewController *vc = self; 102 [self.operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { 103 // 更新进度 104 vc.progressView.progress = ((float)totalBytesRead + downloadedBytes)/ (totalBytesExpectedToRead + downloadedBytes); 105 vc.progressLabel.text = [NSString stringWithFormat:@"%.2f%%",self.progressView.progress * 100]; 106 // 将进度写入缓存文件 107 NSString *progress = [NSString stringWithFormat:@"%.3f",((float)totalBytesRead + downloadedBytes) / ( totalBytesExpectedToRead + downloadedBytes)]; 108 [progress writeToFile:txtFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil]; 109 }]; 110 111 // 下载完成时调用 112 [self.operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) { 113 //把下载完成的文件转移到保存的路径 114 [fileManager moveItemAtPath:tempFilePath toPath:mvFilePath error:nil]; 115 //删除保存进度的txt文档 116 [fileManager removeItemAtPath:txtFilePath error:nil]; 117 } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) { 118 119 }]; 120 121 // 开始操作 122 [self.operation start]; 123 } 124 } else { 125 [sender setTitle:@"开始下载" forState:UIControlStateNormal]; 126 [self.operation cancel]; 127 self.operation = nil; 128 } 129 } 130 131 /** 132 * 计算缓存文件的大小 133 * 134 * @param fileAbsolutePath 文件的绝对路径 135 * 136 * @return 文件的大小 137 */ 138 - (unsigned long long)fileSizeAtPath:(NSString *)fileAbsolutePath { 139 signed long long fileSize = 0; 140 NSFileManager *fileManager = [NSFileManager new]; 141 if ([fileManager fileExistsAtPath:fileAbsolutePath]) { 142 NSError *error = nil; 143 NSDictionary *fileDict = [fileManager attributesOfItemAtPath:fileAbsolutePath error:&error]; 144 if (!error && fileDict) { 145 fileSize = [fileDict fileSize]; 146 } 147 } 148 return fileSize; 149 } 150 151 @end
iOS开发 -------- AFNetworking实现简单的断点下载
标签:
原文地址:http://www.cnblogs.com/lovestarfish/p/4995470.html