无法从Objective C中的Block Code更新UIView

Qua*_*Ali 7 iphone objective-c ios afnetworking

我正在尝试更新标签,以显示要使用AFNetworking Framework 下载的文件的进度.问题是,当我设置的百分比的标签在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];
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*cel 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];
Run Code Online (Sandbox Code Playgroud)