从后台返回时AVCaptureSession失败

我有一个相机预览窗口,90%的时间都运行良好。 但是,有时候,如果返回我的应用程序,如果它在后台,则不会显示预览。 这是我在视图加载时调用的代码:

- (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]; } 

如果发生这种情况,我可以切换到我的偏好视图并再次返回,并且al很好,但这是一个我想要杀死的烦人的bug。 预览窗口是我的故事板中的UIView。

不要在视图加载时启动捕获会话,而是在viewWillAppear上启动它并在viewWillDissapear上停止它。

看起来你的视图控制器在应用程序处于后台时清理了一些内存。 请记住,请确保初始化捕获会话。

懒惰地在私有属性getter方法中分配您的会话,而不是在start方法中,这样可以避免内存泄漏。