我正在尝试使用 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];
另外,当我删除标签更新代码时,该块似乎正在正确更新
答案 0 :(得分: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];