ios 多任务断点下载 AFNetWorking

来源:互联网 发布:数字图像处理算法研究 编辑:程序博客网 时间:2024/05/01 03:30

#import "DownLoadCell.h"


@implementation DownLoadCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{

    self = [superinitWithStyle:stylereuseIdentifier: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:downloadPathappend:YES];

    [dicOperationsetObject:operationforKey:@(tag)];

    operation.userInfo = @{@"keyOp":@(tag)};

    //下载进度回调

    

    __weak AFHTTPRequestOperation *myOp = operation;

    [operation setDownloadProgressBlock:^(NSUInteger bytesRead,longlong totalBytesRead,longlong 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




0 0
原创粉丝点击