//
// ViewController.m
// AFNetWork
//
// Created by mengxianzhi on 15-4-7.
// Copyright (c) 2015年 mengxianzhi. All rights reserved.
//
#import "ViewController.h"
#import "AFNetworking.h"
#import "DownLoadCell.h"
#define KdefaultTag 10
#define URL1 @"http://124.202.164.13/mp4files/50080000058FFE30/pcdowncc.imgo.tv/a61a08d987a596161f029926d3b4e868/5470d75f/c1/2014/dianshiju/jinpaihongniang/201410316d64dac6-10c5-43f0-8ade-fc53b0833d35.fhv.mp4"
#define URL2 @"http://pcdowncc.imgo.tv/c22b568e89664260ea872330ba774741/552b608f/c1/2014/dianshiju/jinpaihongniang/2014103198b69041-6f7a-46fd-b0b5-066937cda764.fhv.mp4"
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
NSMutableDictionary *dicOperation;
UILabel *lable;
NSArray *downloadUrlList;
NSString *downUrl;
UITableView *tabView;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
downloadUrlList = [[NSArray alloc]initWithObjects:URL1,URL2,nil];
CGSize size = self.view.frame.size;
tabView = [[UITableView alloc]initWithFrame:CGRectMake(0,20, size.width, size.height) style:UITableViewStylePlain];
[tabView setDataSource:self];
[tabView setDelegate:self];
[self.view addSubview:tabView];
dicOperation = [[NSMutableDictionary alloc]init];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
DownLoadCell *cell = [[DownLoadCell alloc]init];
[cell.button setTag:KdefaultTag + indexPath.row];
[cell.button addTarget:self action:@selector(beginDown:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 2;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tabView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)beginDown:(UIButton *)sender{
int downLoadTag = (int)sender.tag - KdefaultTag;
downUrl = [downloadUrlList objectAtIndex:downLoadTag];
if (!sender.selected) {
[self startDownload:downLoadTag];
}else{
AFHTTPRequestOperation *currentOp = [dicOperation objectForKey:@(downLoadTag)];
[currentOp pause];
}
sender.selected = !sender.selected;
}
//获取已下载的文件大小
- (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:(int)tag {
NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *arrUrlList = [downUrl componentsSeparatedByString:@"/"];
NSString *videoName = [arrUrlList objectAtIndex:arrUrlList.count-1];
NSString *downloadPath = [cacheDirectory stringByAppendingPathComponent:videoName];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:downUrl]];
//检查文件是否已经下载了一部分
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];
[dicOperation setObject:operation forKey:@(tag)];
operation.userInfo = @{@"keyOp":@(tag)};
//下载进度回调
__weak AFHTTPRequestOperation *myOp = operation;
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
//下载进度
float progress = ((float)totalBytesRead + downloadedBytes) / (totalBytesExpectedToRead + downloadedBytes);
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[[myOp.userInfo objectForKey:@"keyOp"] intValue] inSection:0];
DownLoadCell *cell = (DownLoadCell *)[tabView cellForRowAtIndexPath:indexPath];
NSString *str = [NSString stringWithFormat:@"下载%.4f",progress];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"------------------------ 第%d Cell 下载了 %@",[[myOp.userInfo objectForKey:@"keyOp"] intValue],str);
[cell.lable setText:str];
});
}];
//成功和失败回调
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[[myOp.userInfo objectForKey:@"keyOp"] intValue] inSection:0];
DownLoadCell *cell = (DownLoadCell *)[tabView cellForRowAtIndexPath:indexPath];
dispatch_async(dispatch_get_main_queue(), ^{
[cell.button setTitle:@"完成" forState:UIControlStateSelected];
[cell.button setUserInteractionEnabled:NO];
[cell.lable setText:@"100%"];
});
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[operation start];
}
@end
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#import "DownLoadCell.h"
@implementation DownLoadCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button setTitle:@"开始" forState:UIControlStateNormal];
[_button setTitle:@"暂停" forState:UIControlStateSelected];
[_button setFrame:CGRectMake(200, 0, 100, 40)];
[_button setBackgroundColor:[UIColor redColor]];
_lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
[_lable setBackgroundColor:[UIColor cyanColor]];
[self.contentView addSubview:_lable];
[self.contentView addSubview:_button];
}
return self;
}
@end