AVCaptureSession fails when returning from backgro

2019-04-29 12:30发布

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.

1条回答
等我变得足够好
2楼-- · 2019-04-29 12:54

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.

查看更多
登录 后发表回答