从后台返回时AVCaptureSession失败 [英] AVCaptureSession fails when returning from background

查看:314
本文介绍了从后台返回时AVCaptureSession失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相机预览窗口,它可以在90%的时间内正常工作。但是,有时候,如果返回我的应用程序,如果它在后台,则不会显示预览。这是我在视图加载时调用的代码:

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

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

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.

推荐答案

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

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.

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

Allocate your session lazily in a private property getter method rather than in your start method you will avoid memory leaks this way.

这篇关于从后台返回时AVCaptureSession失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆