#import "DownLoadCell.h"
@implementation DownLoadCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
self = [superinitWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
_button = [UIButtonbuttonWithType:UIButtonTypeCustom];
[_buttonsetTitle:@"開始"forState:UIControlStateNormal];
[_buttonsetTitle:@"暫停"forState:UIControlStateSelected];
[_button setFrame:CGRectMake(200, 0, 100, 40)];
[_buttonsetBackgroundColor:[UIColorredColor]];
_lable = [[UILabelalloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
[_lablesetBackgroundColor:[UIColorcyanColor]];
[self.contentViewaddSubview:_lable];
[self.contentViewaddSubview:_button];
}
returnself;
}
@end
----------------------------------------------------------------------------------------------------------------------
#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 longlong)fileSizeForPath:(NSString *)path {
signed longlong 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 = [downUrlcomponentsSeparatedByString:@"/"];
NSString *videoName = [arrUrlListobjectAtIndex:arrUrlList.count-1];
NSString *downloadPath = [cacheDirectorystringByAppendingPathComponent:videoName];
NSURLRequest *request = [NSURLRequestrequestWithURL:[NSURLURLWithString:downUrl]];
//檢查檔案是否已經下載了一部分
unsigned longlong downloadedBytes = 0;
if ([[NSFileManagerdefaultManager] fileExistsAtPath:downloadPath]) {
//擷取已下載的檔案長度
downloadedBytes = [selffileSizeForPath:downloadPath];
if (downloadedBytes > 0) {
NSMutableURLRequest *mutableURLRequest = [requestmutableCopy];
NSString *requestRange = [NSStringstringWithFormat:@"bytes=%llu-", downloadedBytes];
[mutableURLRequest setValue:requestRangeforHTTPHeaderField:@"Range"];
request = mutableURLRequest;
}
}
//不使用緩衝,避免斷點續傳出現問題
[[NSURLCachesharedURLCache] removeCachedResponseForRequest:request];
//下載請求
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperationalloc] initWithRequest:request];
//下載路徑
operation.outputStream = [NSOutputStreamoutputStreamToFileAtPath:downloadPath append:YES];
[dicOperationsetObject: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