如何使用AFNetworking AFHTTPRequestOperationManager显示ProgressBar

时间:2015-06-28 08:28:45

标签: ios objective-c afnetworking-2 uiprogressview

我正在尝试显示进度条,因为我从网址下载了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);
  }];

2 个答案:

答案 0 :(得分:5)

您在成功块中设置了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;
}];

答案 1 :(得分:2)

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)

你什么也没做。这足以显示您的观点的进展。