Search code examples
iosobjective-cxcodeavcapturesessionviewdidload

Set Background Camera behind UILabels


I have been trying for very long and could not get it to work out but basically I would like to display the live camera feed in the background behind my labels and buttons. Here is the code I am working with to make the camera appear

   - (void)viewDidLoad {
    [super viewDidLoad];

    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    session.sessionPreset = AVCaptureSessionPresetHigh;

    AVCaptureDevice *device = [AVCaptureDevice  defaultDeviceWithMediaType:AVMediaTypeVideo];

    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    [session addInput:input];

    AVCaptureVideoPreviewLayer *newCaptureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
    newCaptureVideoPreviewLayer.frame = self.view.bounds;

    [self.view addSublayer:newCaptureVideoPreviewLayer.view];
    [self.view sendSubviewToBack:newCaptureVideoPreviewLayer.view];

    [session startRunning];

}

I do not know how to place it behind the labels on the view did load. Any help would be much appreciated!


Solution

  • You just need to add the view in background by using sendSubviewToBack

    For more detail you can check Apple AVCam Example

    sendSubviewToBack: Moves the specified subview so that it appears behind its siblings.

    AVCaptureVideoPreviewLayer *newCaptureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
    newCaptureVideoPreviewLayer.frame = self.view.bounds;
    
    [self.view.layer addSublayer:newCaptureVideoPreviewLayer];
    [session startRunning];
    

    OR

    [[self.view superView] insertSubview:newCaptureVideoPreviewLayer belowSubview:self.view];