通常使用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
下載的地址如果實效了,請自行替換掉。