我没有太多使用信号量的经验,也没有使用块的经验。我已经看到了关于如何将异步调用转换为同步调用的各种建议。在这种情况下,在拍摄另一张照片之前,我只想等待确定iPhone的镜头已经改变了焦点。我添加了一个完成块(使用一个小例程来证明我看到了它)。但是如何阻塞我的其余代码(在主线程上运行),直到我得到完成回调?
- (void) changeFocusSettings
{
if ([SettingsController settings].useFocusSweep)
{
// increment the focus setting
float tmp = [SettingsController settings].fsLensPosition;
float fstmp =[[SettingsController settings] nextLensPosition: [SettingsController settings].fsLensPosition]; // get next lensposition
[SettingsController settings].fsLensPosition = fstmp ;
tmp = [SettingsController settings].fsLensPosition;
if ([self.captureDevice lockForConfiguration: nil] == YES)
{
__weak typeof(self) weakSelf = self;
[self.captureDevice setFocusModeLockedWithLensPosition:tmp
completionHandler:^(CMTime syncTime) {
NSLog(@"focus over..time = %f", CMTimeGetSeconds(syncTime));
[weakSelf focusCompletionHandler : syncTime];
}];
}
}
}
- (bool) focusCompletionHandler : (CMTime)syncTime
{
NSLog(@"focus done, time = %f", CMTimeGetSeconds(syncTime));
return true;
}changeFocusSettings完全是从另一个例程调用的。我想象一下在changeFocusSettings内部设置的某种信号量,然后focuscompletionHandler将其重置。但细节超出了我的能力。
谢谢。
发布于 2017-08-16 02:19:55
我自己解决了这个问题,一点也不难,而且看起来还不错。这是代码,以防它对其他人有帮助。如果你碰巧发现了一个错误,请告诉我。
dispatch_semaphore_t focusSemaphore;
...
- (bool) focusCompletionHandler : (CMTime)syncTime
{
dispatch_semaphore_signal(focusSemaphore);
return true;
}
- (void) changeFocusSettings
{
focusSemaphore = dispatch_semaphore_create(0); // create semaphone to wait for focuschange to complete
if ([SettingsController settings].useFocusSweep)
{
// increment the fsLensposition
float tmp = [SettingsController settings].fsLensPosition;
float fstmp =[[SettingsController settings] nextLensPosition: [SettingsController settings].fsLensPosition]; // get next lensposition
[SettingsController settings].fsLensPosition = fstmp ;
tmp = [SettingsController settings].fsLensPosition;
NSLog(@"focus setting = %f and = %f", tmp, fstmp);
if ([self.captureDevice lockForConfiguration: nil] == YES)
{
__weak typeof(self) weakSelf = self;
[self.captureDevice setFocusModeLockedWithLensPosition:tmp
completionHandler:^(CMTime syncTime) {
[weakSelf focusCompletionHandler : syncTime];
}];
dispatch_semaphore_wait(focusSemaphore, DISPATCH_TIME_FOREVER);
}
}
}https://stackoverflow.com/questions/45642585
复制相似问题