iphone - 无法从 Objective C 中的 block 代码更新 UIView

标签 iphone ios objective-c afnetworking

我正在尝试使用 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];

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

最佳答案

您需要在主线程上调用所有 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];

关于iphone - 无法从 Objective C 中的 block 代码更新 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16897703/

相关文章:

iphone - Objective-C : Accessing constants from other classes

iphone - 有没有人因为使用设备 UDID 而被 Apple 拒绝了他们的 iOS 应用程序?

iphone - 有多少 iPhone 应用程序可以在 Linux 上开发和测试?

iphone - 通过C与iDevice通信?

ios - RxSwift 验证按钮颜色设置不正确

objective-c - 访问 iPhone 通知

ios - 使用核心动画对轨迹变化进行动画处理

iOS : How using different size image with the same name in Assets. xcassets 在不同设备或不同景观上运行时

iOS 10 : issue with timezone when dealing with dates from HealthKit

objective-c - 如何使用代码旋转 iOS 模拟器?