Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVCaptureSession fails when returning from background

I have a camera preview window which is working well 90% of the time. Sometimes however, when returning to my app if it's been in the background, the preview will not display. This is the code I call when the view loads:

- (void) startCamera {

session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPresetPhoto;

AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
captureVideoPreviewLayer.frame = _cameraView.bounds;
[_cameraView.layer addSublayer:captureVideoPreviewLayer];
captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
captureVideoPreviewLayer.position=CGPointMake(CGRectGetMidX(_cameraView.bounds), 160);

AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;

AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {

    NSLog(@"ERROR: %@", error);


    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Important!"
                                                    message:@"Unable to find a camera."
                                                   delegate:nil
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil];
    [alert show];
    [alert autorelease];
}

[session addInput:input];

stillImage = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG , AVVideoCodecKey, nil];
[stillImage setOutputSettings:outputSettings];

[session addOutput:stillImage];
[session startRunning];
}

If this happens, I can switch to my preferences view and back again and al is well,but it's an annoying bug I'd like to kill. The preview window is a UIView in my storyboard.

like image 758
mrEmpty Avatar asked Jun 04 '12 20:06

mrEmpty


1 Answers

Do not start the capture session on view load, instead start it on viewWillAppear and stop it on viewWillDissapear.

Seems like your view controller is cleaning up some memory when the app is in the background. Make sure you are initializing your capture session with this in mind.

Allocate your session lazily in a private property getter method rather than in your start method you will avoid memory leaks this way.

like image 129
Chris Heyes Avatar answered Sep 28 '22 09:09

Chris Heyes