Domanda

I'm trying to get the feed from the ios device's camera to display on screen and I don't want to use the ImagePickerController because I want to have more control over the look of the view on screen and I want to have more control over the camera's aperture and sample rate.

Here's the code I'm using in my UIViewController's viewDidLoad method:

//Setting up the camera
AVCaptureSession *captureSession = [[AVCaptureSession alloc] init];
//This gets the back camera, which is the default video avcapturedevice
AVCaptureDevice *camera = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
AVCaptureDeviceInput *cameraInput = [AVCaptureDeviceInput deviceInputWithDevice:camera error:&error];
if (cameraInput) {
    [captureSession addInput:cameraInput];
}
else {
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Camera not found" message:@"Your device must have a camera in order to use this feature" delegate:Nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}
AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:captureSession];
UIView* cameraView = [[UIView alloc] initWithFrame:self.view.bounds];
previewLayer.frame = cameraView.bounds; 
previewLayer.videoGravity = @"AVLayerVideoGravityResizeAspect";
[cameraView.layer addSublayer:previewLayer];
[self.view addSubview:cameraView];

Yet nothing appears on the screen when the view loads, and I don't get an error message. Any idea what I'm missing?

È stato utile?

Soluzione

You never actually start the capture session in the code that you have shown:

[captureSession startRunning];

Also, I would recommend that you look at the AVCam sample code that Apple has provided to see how they setup their capture session and preview layer. It contains some good tips regarding how to manage your capture session (they dispatch everything to a custom serial queue). For example, it contains these comments in the code:

// In general it is not safe to mutate an AVCaptureSession or any of its inputs, outputs, or connections from multiple threads at the same time.
// Why not do all of this on the main queue?
// -[AVCaptureSession startRunning] is a blocking call which can take a long time. We dispatch session setup to the sessionQueue so that the main queue isn't blocked (which keeps the UI responsive).
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top