【问题标题】:AVCaptureSession fails when returning from background从后台返回时 AVCaptureSession 失败
【发布时间】:2012-06-04 20:58:37
【问题描述】:

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

【问题讨论】:

    标签: iphone ios uiview avcapturesession


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢,我会这样做并测试几个小时:)
    • 等等 - 难道viewWillAppear / Disappear 仅在您的应用程序中移动场景时才被调用:当应用程序进出前台时它们不会被调用?不需要注册UIApplicationWillResignActiveNotification 并使用它吗? QA with example of that
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多