在progressHandler(iOS)中强制执行主队列

时间:2018-06-12 07:50:29

标签: ios objective-c multithreading uiimage phasset

我正在使用requestImageDataForAsset从云端下载图像。我附加了一个PHImageRequestOptions和进度处理程序,以定期获得下载进度的通知。在进程处理程序中,我正在绘制进度UIImage并使用此图像刷新UIButton。

但是进度处理程序加载到后台队列中,我需要在主线程上刷新UIButton图像。

我的问题是主线程只有在完全下载完成后才会执行。

有没有办法在给定时刻强制执行主线程?

        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        options.progressHandler = ^(double progress, NSError * _Nullable error, BOOL * _Nonnull stop, NSDictionary * _Nullable info) {
            NSLog(@"Progress: %f %%",progress*100.f);
            UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
            CGContextRef ctx = UIGraphicsGetCurrentContext();

            <create UIImage>
            progressImg=UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"Updating button image");
                [self->testButton setImage:progressImg forState:UIControlStateNormal];
                [self->testButton setNeedsDisplay];
            });
        };

        [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info)
        {
             <actions>
        }];

接收输出:

2018-06-12 10:30:34.765372+0300 App[12894:2931379] Progress: 0.000000 %
2018-06-12 10:30:34.828532+0300 App[12894:2931379] Progress: 0.000000 %
2018-06-12 10:30:35.724429+0300 App[12894:2931379] Progress: 0.000000 %
2018-06-12 10:30:41.703484+0300 App[12894:2931379] Progress: 0.042285 %
2018-06-12 10:30:44.241504+0300 App[12894:2931379] Progress: 5.973034 %
2018-06-12 10:30:44.581450+0300 App[12894:2931410] Progress: 62.652379 %
2018-06-12 10:30:44.753667+0300 App[12894:2931379] Progress: 99.009919 %
2018-06-12 10:30:44.756178+0300 App[12894:2931379] Progress: 100.000000 %
2018-06-12 10:30:44.859165+0300 App[12894:2931410] Progress: 100.000000 %
2018-06-12 10:30:44.884380+0300 App[12894:2931279] Updating button image
2018-06-12 10:30:44.884484+0300 App[12894:2931279] Updating button image
2018-06-12 10:30:44.884550+0300 App[12894:2931279] Updating button image
2018-06-12 10:30:44.884600+0300 App[12894:2931279] Updating button image
2018-06-12 10:30:44.884646+0300 App[12894:2931279] Updating button image
2018-06-12 10:30:44.884693+0300 App[12894:2931279] Updating button image
2018-06-12 10:30:44.884745+0300 App[12894:2931279] Updating button image
2018-06-12 10:30:44.884797+0300 App[12894:2931279] Updating button image
2018-06-12 10:30:44.884843+0300 App[12894:2931279] Updating button image

1 个答案:

答案 0 :(得分:0)

问题来自我需要设置options.synchronous = NO

的选项