dispatch_semaphore_signal never being executed bec

2019-09-14 18:37发布

I am trying to take two pictures and want them to run in order. The method for capturing pictures is done using a method that runs asynchronously. I currently use semaphores to try to synchronize this, but it stops the program from running. I believe this is because the completionHandler is run on the same thread, and since the thread is locked, it can't execute to free the semaphore. Here is my current code:

    camera_sema = dispatch_semaphore_create(0);


    [photoOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageSampleBuffer, NSError *error)
     {
         [flash turnOffFlash];//turning off flash for second picture
        //perform needed work

         dispatch_semaphore_signal(camera_sema);
     }];
    dispatch_semaphore_wait(camera_sema, DISPATCH_TIME_FOREVER);

 Is there a way I can use dispatch_async for this case or a way to run the completionHandler on another background thread so it is able to execute?

UPDATE 1: This works but not sure if its the best way to do it.

-(void*)method: (int) iteration {
[photoOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageSampleBuffer, NSError *error)
     {
         [flash turnOffFlash];//turning off flash for second picture
        //perform needed work
        //base case
        [method: iteration-1];

     }];
}

So basically I call the method recursively to ensure that it only repeats once the callback has been reached. It will essentially run an async task synchronously. Unfortunately, for the final design, I need to be able to run it infinitely. Doing this recursively will fail. Please let me know if there is better way to do this.

0条回答
登录 后发表回答