2017-08-11 67 views
0

我沒有太多的信號量經驗,也沒有太多的經驗。我已經看到了關於如何將異步調用轉換爲同步調用的各種建議。在這種情況下,我只想等待確保iPhone的鏡頭在拍攝另一張照片之前已經改變了焦點。 我已經添加了一個完成塊(用一個小程序來證明我看到它)。但是,如何阻止我的代碼(在主線程上運行)的其餘部分,直到我獲得完成回調?需要等待完成setFocusModeLockedWithLensPosition - Semaphore?原子? NSCondition?

- (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重置它。但細節超出了我。
謝謝。

回答

0

我自己完成了它,它並不難,它似乎工作。這裏的代碼可以幫助別人。如果您碰巧發現錯誤,請告訴我。

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); 
     } 
    } 
}