7

我正在尝试更新标签以显示要使用AFNetworking框架下载的文件的进度。问题是,当我将百分比设置为setProgressiveDownloadProgressBlock 中的标签时,标签仅在下载开始和下载完成时更新。

 __weak MTCViewController *weakSelf= self; 
[_operation setProgressiveDownloadProgressBlock:^(AFDownloadRequestOperation *operation, NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {
        float percent = (float)(totalBytesRead / totalBytesExpectedToReadForFile)*100;;
       // [weakSelf updateProgress:percent];
        [weakSelf updateText:[NSString stringWithFormat:@"Progress = %f",percent]];
    }];
    [_operation start];

另外,当我删除标签更新代码时,块似乎正在正确更新

4

1 回答 1

7

您需要在主线程上调用所有 UI 更改。因此,计算百分比,然后从主线程调度更新 UI 的代码:

__weak MTCViewController *weakSelf= self; 
[_operation setProgressiveDownloadProgressBlock:^(AFDownloadRequestOperation *operation, NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {
    float percent = ((float)totalBytesRead / (float)totalBytesExpectedToReadForFile)*100;
      dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf updateText:[NSString stringWithFormat:@"Progress = %f", round(percent)]];
      });
}];
[_operation start];
于 2013-06-03T13:38:58.193 回答