AVCaptureSession fails when returning from background

Go To StackoverFlow.com

6

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.

2012-06-04 20:58
by mrEmpty


8

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.

2012-06-04 21:02
by Chris Heyes
Thank you, I'll do that and test it for a few hours : - mrEmpty 2012-06-04 21:12
fantastic solution...... - Paresh Navadiya 2013-09-26 11:16
Wait - isn't it the case that viewWillAppear / Disappear are only called as the scene moves around in your app: they are not called as the app goes in and out of foreground? Wouldn't it be necessary to register for UIApplicationWillResignActiveNotification and use that? QA with example of thatFattie 2016-07-31 13:01
Ads