iOS AVCaptureVideoPreviewLayer not showing in UIView? iOS AVCaptureVideoPreviewLayer not showing in UIView? xcode xcode

iOS AVCaptureVideoPreviewLayer not showing in UIView?


Had the same issue and the key was setting the AVCaptureVideoPreviewLayer's frame to the bounds of the UIView:

// Setup camera preview imageAVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_captureSession];previewLayer.frame = _cameraPreview.bounds;[_cameraPreview.layer addSublayer:previewLayer];


I had a similar issue in my project. From your code excerpt, it is hard to tell who is invoking setupAVCapture method. In my case, I had to ensure that AVCaptureVideoPreviewLayer is created on the main thread.

There are couple of options. You can invoke setupAVCapture on the main application thread by wrapping the call in the following block:

dispatch_async(dispatch_get_main_queue(), ^{   // call setupAVCapture() method in here});

If that is not an option, you can only do that on the following part of your code:

  dispatch_async(dispatch_get_main_queue(), ^{    previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];    [previewLayer setBackgroundColor:[[UIColor blackColor] CGColor]];    [previewLayer setVideoGravity:AVLayerVideoGravityResizeAspect];    CALayer *rootLayer = [previewView layer];    [rootLayer setMasksToBounds:YES];    [previewLayer setFrame:[rootLayer bounds]];    [rootLayer addSublayer:previewLayer];   });


It's very important to set frame on the main thread.

Swift 5

let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)previewLayer.videoGravity = .resizeAspectFilllayer.addSublayer(previewLayer)DispatchQueue.main.async {  previewLayer.frame = self.bounds}