[英]how to wait for the URLSession to finish before returning the result from a function in Swift 3
[英]How to wait for a delegate function to finish before returning value from main function
我有一个用于捕获真实深度相机信息的自定义函数,并且在委托函数完成对捕获的照片的处理之前会返回该函数。 我需要以某种方式等到所有代表都完成后才能返回正确的值。
我尝试将主函数调用包装到一个同步块中,但是并不能解决问题。
- (NSDictionary *)capture:(NSDictionary *)options resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject
{
if (@available(iOS 11.1, *)) {
// Set photosettings to capture depth data
AVCapturePhotoSettings *photoSettings = [AVCapturePhotoSettings photoSettingsWithFormat:@{AVVideoCodecKey : AVVideoCodecJPEG}];
photoSettings.depthDataDeliveryEnabled = true;
photoSettings.depthDataFiltered = false;
@synchronized(self) {
[self.photoOutput capturePhotoWithSettings:photoSettings delegate:self];
}
}
// Somehow need to wait here until the delegate functions finish before returning
return self.res;
}
被调用为时已晚的委托函数:
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error
{
Cam *camera = [[Cam alloc] init];
self.res = [camera extractDepthInfo:photo];
}
当前,在调用委托之前,将返回nil
,只有在此之后,委托函数才将所需的结果分配给self.res
我相信您正在寻找的是dispatch_semaphore_t
。
信号量使您可以锁定线程,直到执行辅助操作为止。 这样,您可以将方法的返回推迟到委托返回之前(如果您正在辅助线程上进行操作)。
这种方法的问题是您将锁定线程! 因此,如果您在主线程中操作,则您的应用将无响应。
我建议您考虑将响应移至完成框,类似于:
-(void)capture:(NSDictionary *)options resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject completion:(void (^)(NSDicitionary* ))completion {
self.completion = completion
...
}
并在最后调用完成:
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error
{
Cam *camera = [[Cam alloc] init];
self.res = [camera extractDepthInfo:photo];
self.completion(self.res);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.