你好,歡迎來到IOS教程網

 Ios教程網 >> IOS訊息 >> 關於IOS >> ios使用AFN框架下載文件顯示下載百分比帶進度條

ios使用AFN框架下載文件顯示下載百分比帶進度條

編輯:關於IOS

通常使用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

下載的地址如果實效了,請自行替換掉。

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved