网上只写了一个文件断点下载的例子! 我仿照别人得例子 自己增加了自己代码,异步下载文件 支持断点下载 多任务下载! 如有问题 请联系我

//

//  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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值