Live camera in UIImageView

2019-06-02 11:27发布

问题:

Does anybody know how I can get a live camera feed into an UIImageView?

I have a custom UI where I need to show the camera feed (front facing camera) so I cannot use the UIImagePickerControl.

回答1:

You need to create a capture session, and start it running. Once that's done you can add the layer from the capture session to your view:

- (void)setupCaptureSession
{
    NSError* error = nil;

    // Create the session
    _captureSession = [[AVCaptureSession alloc] init];    
    _captureSession.sessionPreset = AVCaptureSessionPresetMedium;
    AVCaptureDevice* device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    AVCaptureDeviceInput* input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];

    [_captureSession addInput:input];
    AVCaptureVideoDataOutput* output = [[AVCaptureVideoDataOutput alloc] init];
    [_captureSession addOutput:output];

    // Configure your output.
   dispatch_queue_t queue = dispatch_queue_create("myCameraOutputQueue", NULL);
   //If you want to sebsequently use the data, then implement the delegate.
   [output setSampleBufferDelegate:self queue:queue]; 
}

Having done that, you can create a preview layer as follows:

_previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_captureSession];
[_captureSession startRunning];

And then add the preview layer to your view:

_myView.layer addSubLayer:_previewLayer];