-->

AVCaptureSession从后台返回时出现故障(AVCaptureSession fails

2019-09-17 18:09发布

我这是工作的时间以及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];
}

如果发生这种情况,我可以切换到我的喜好视图,然后再返回和人是很好的,但它是一个恼人的错误,我想杀人。 预览窗口在我的故事板一个UIView。

Answer 1:

不要一开始就视负载捕获会话,而不是启动它在viewWillAppear中,并停止它viewWillDissapear。

好像你的视图控制器清理一些内存时,应用程序是在后台。 确保你考虑到这一点初始化您的捕获会话。

懒洋洋地分配在一个私人财产的getter方法,而不是在你的启动方法,你会避免内存泄漏这样您的会话。



文章来源: AVCaptureSession fails when returning from background