ios使用AFN框架下载文件显示下载百分比带进度条

通常使用afn下载文件用到的是AFURLSessionManager,如果要显示百分百,需要用AFHTTPRequestOperation类。关于这个类,官方的说法是这样的:

Although AFHTTPRequestOperationManager is usually the best way to go about making requests,AFHTTPRequestOperation can be used by itself.

虽然不是推荐的,但可以用就对了。

使用MBProgressHUD显示进度条,关键代码在一下方法中:

- (IBAction)downloadFile:(id)sender {
    //初始化进度条
    MBProgressHUD *HUD = [[MBProgressHUD alloc]initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.tag=1000;
    HUD.mode = MBProgressHUDModeDeterminate;
    HUD.labelText = @"Downloading...";
    HUD.square = YES;
    [HUD show:YES];
    //初始化队列
    NSOperationQueue *queue = [[NSOperationQueue alloc ]init];
    //下载地址
    NSURL *url = [NSURL URLWithString:@"http://help.adobe.com/archive/en/photoshop/cs6/photoshop_reference.pdf"];
    //保存路径
    NSString *rootPath = [self dirDoc];
    _filePath= [rootPath  stringByAppendingPathComponent:@"file.pdf"];
    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc]initWithRequest:[NSURLRequest requestWithURL:url]];
    op.outputStream = [NSOutputStream outputStreamToFileAtPath:_filePath append:NO];
    // 根据下载量设置进度条的百分比
    [op setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        CGFloat precent = (CGFloat)totalBytesRead / totalBytesExpectedToRead;
        HUD.progress = precent;
    }];
    
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"下载成功");
        [HUD removeFromSuperview];
        [self performSegueWithIdentifier:@"showDetail" sender:nil];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"下载失败");
        [HUD removeFromSuperview];
    }];
    //开始下载
    [queue addOperation:op];
}


//获取Documents目录
-(NSString *)dirDoc{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return documentsDirectory;
}

demo地址:https://github.com/WorthyZhang/DownloadWithProgressBarDemo

下载的地址如果实效了,请自行替换掉。


你可能感兴趣的:(iOS学习笔记)