一:本示例代码包括:
- 文件下载,写入指定目录
- 下载进度,回调Progress;
- 断点续传,下载暂停,继续操作;
二:本项目 适用于 AFNetworking 1.x 版本
1 #pragma mark 断点续传下载; 2 3 //断点下载续传--需要服务器端的支持,本次测试为下载百度音乐,此接口,会在第二次暂停,继续下载时,出404错误; 4 5 //进度 6 UIProgressView *downProgressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault]; 7 downProgressView.center = CGPointMake(self.view.center.x, 20); 8 downProgressView.progress = 0; 9 downProgressView.progressTintColor = [UIColor blueColor];10 downProgressView.trackTintColor = [UIColor grayColor];11 [self.view addSubview:downProgressView];12 13 //开始14 UIButton *start = [UIButton buttonWithType:UIButtonTypeRoundedRect];15 start.frame = CGRectMake(25, 40, 80, 30);16 [start setTitle:@"开始" forState:UIControlStateNormal];17 [start addTarget:self action:@selector(startDownloadOp) forControlEvents:UIControlEventTouchUpInside];18 19 //暂停20 UIButton *pause = [UIButton buttonWithType:UIButtonTypeRoundedRect];21 pause.frame = CGRectMake(125, 40, 80, 30);22 [pause setTitle:@"暂停" forState:UIControlStateNormal];23 [pause addTarget:self action:@selector(pausetDownloadOp) forControlEvents:UIControlEventTouchUpInside];24 25 //继续26 UIButton *resume = [UIButton buttonWithType:UIButtonTypeRoundedRect];27 resume.frame = CGRectMake(220, 40, 80, 30);28 [resume setTitle:@"继续" forState:UIControlStateNormal];29 [resume addTarget:self action:@selector(resumeDownloadOp) forControlEvents:UIControlEventTouchUpInside];30 31 [self.view addSubview:start];32 [self.view addSubview:pause];33 [self.view addSubview:resume];34 35 //文件名36 NSString *fileName = [NSString stringWithFormat:@"%@愿得一人听.mp3",NSTemporaryDirectory()];37 NSLog(@"%@",fileName);38 39 //下载40 NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:MusicOne]];41 self.downloadMusicOP = [[AFHTTPRequestOperation alloc]initWithRequest:downloadRequest];42 _downloadMusicOP.outputStream = [NSOutputStream outputStreamToFileAtPath:fileName append:NO];43 44 [_downloadMusicOP setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {45 CGFloat progress = ((float)totalBytesRead) / totalBytesExpectedToRead;46 [downProgressView setProgress:progress animated:YES];47 start.enabled = NO;48 [start setTitle:@"下载中" forState:UIControlStateNormal];49 }];50 51 [_downloadMusicOP setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {52 start.enabled = NO;53 [start setTitle:@"完成" forState:UIControlStateNormal];54 NSLog(@"download finish");55 NSLog(@"%@",[[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:nil]);56 57 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {58 NSLog(@"error %@",error);59 }];60 61 62 63 64 65 }66 67 #pragma mark AFNetworking 下载之断点续传;68 69 - (void)startDownloadOp70 {71 [_downloadMusicOP start];72 }73 74 - (void)pausetDownloadOp75 {76 [_downloadMusicOP pause];77 }78 79 - (void)resumeDownloadOp80 {81 [_downloadMusicOP resume];82 }
项目代码: