从后台返回时 AVCaptureSession 失败

2024-01-19

我有一个相机预览窗口,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。


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

当应用程序在后台运行时,您的视图控制器似乎正在清理一些内存。确保在初始化捕获会话时牢记这一点。

在私有属性 getter 方法中而不是在启动方法中延迟分配会话,这样可以避免内存泄漏。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从后台返回时 AVCaptureSession 失败 的相关文章

随机推荐