Michal
Michal

Reputation: 15669

UIView unchanged when modified from dispatch_async

I have a subview with live view from the back camera. I am animating it when toggling the camera to front. Because I could't sync the animation and the toggle, I covered it with another view with plain black background. Because toggle is slower, I want to remove the black subview after toggle was performed. But when I do it, it won't disappear. Debugger shows all NSLogs I put in, and the debugger even stops when I put breakpoints anywhere, so the code is reachable. But the UIView is simply not modified and still holds the black subview.

Interesting fact: when I turn display off with the top button and then back on again, the black view is gone!

CODE:

- (IBAction)cameraChanged:(id)sender {
NSLog(@"Camera changed");
UIView *animView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.videoPreviewView.frame.size.width, self.videoPreviewView.frame.size.height)];
animView.tag = 42;
[animView setBackgroundColor:[UIColor blackColor]];

[UIView transitionWithView:self.videoPreviewView duration:1.0
                    options:self.animate ? UIViewAnimationOptionTransitionFlipFromLeft:UIViewAnimationOptionTransitionFlipFromRight
                animations:^{
                    [self.videoPreviewView addSubview:animView];
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul), ^{
                        [self.captureManager toggleCamera];
                        NSLog(@"Done toggling");
                        [self done];
                    });
                }
                completion:^(BOOL finished){
                    if (finished) {
                        //
                    }
                }];
self.animate = !self.animate;
}

- (void)done {
for (UIView *subview in [self.videoPreviewView subviews]) {
    NSLog(@"In for");
    if (subview.tag == 42) {
        NSLog(@"removing");
        [subview removeFromSuperview];
    }
}
}

Anybody knows why is this happening and how to solve it?

Upvotes: 0

Views: 1453

Answers (1)

brianLikeApple
brianLikeApple

Reputation: 4371

UIView Update should be run on Main thread.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul), ^{
//BlahBlah
        dispatch_sync(dispatch_get_main_queue(), ^{
        //update your UIView
        });
    });

Upvotes: 4

Related Questions