如何使用 AFNetworking AFHTTPRequestOperationManager 显示 ProgressBar[英] How to show ProgressBar With AFNetworking AFHTTPRequestOperationManager

本文是小编为大家收集整理的关于如何使用 AFNetworking AFHTTPRequestOperationManager 显示 ProgressBar的处理方法,想解了如何使用 AFNetworking AFHTTPRequestOperationManager 显示 ProgressBar的问题怎么解决?如何使用 AFNetworking AFHTTPRequestOperationManager 显示 ProgressBar问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

当我从 url 下载 JSON 时,我试图显示进度条.JSON 正在正确下载,但我不确定如何显示进度条.我曾尝试使用 UIProgressView 但它没有显示在屏幕上.任何建议将不胜感激.

CGFloat width = [UIScreen mainScreen].bounds.size.width;
CGFloat height = [UIScreen mainScreen].bounds.size.height;

CGRect rect = CGRectMake(width/2, height/2, width/5, height/5);
UIProgressView *myProgressView = [[UIProgressView alloc]initWithFrame:rect];
myProgressView.progressViewStyle = UIProgressViewStyleBar;
[self.view addSubview:myProgressView];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];    
[manager GET:@"https:urlWithJson" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
      [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
       {
           myProgressView.progress = (float)totalBytesRead / totalBytesExpectedToRead;
       }];
      [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
          NSLog(@"operation Completed");
      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          NSLog(@"ERROR");
      }];

      [operation start];
  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      NSLog(@"timeout Error: %@", error);
  }];

推荐答案

你在success块里面设置了download-progress-block,有点晚了;)

试试这个:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];    
AFHTTPRequestOperation *operation = [manager GET:@"https:urlWithJson" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Complete");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
    myProgressView.progress = (float)totalBytesRead / totalBytesExpectedToRead;
}];

其他推荐答案

Swift 的简单解决方案:

let progress: UIProgressView? //for example, reference to IBOutlet
let manager = AFHTTPRequestOperationManager()
let operation = manager.POST(query, parameters: parameters, constructingBodyWithBlock: { multipartData in

             //do sth with your multipartData
    }, success: { operation, response in

            //success
    }) { operation, error in

            //failure
}

progress?.setProgressWithUploadProgressOfOperation(operation!, animated: true)

你什么都不做.这足以显示您的视图进度.

本文地址:https://www.itbaoku.cn/post/924530.html