首页 > 解决方案 > 当我尝试在 AVPlayer 中输入背景时,“无法添加输出”崩溃

问题描述

我已经编写了代码,这样当我进入后台并返回相机会话时,就不应该搞砸了,但事实并非如此。当您返回时,我收到以下错误:

2019-01-29 18:04:57.702967-0500 Proj[2105:617183] * 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“* -[AVCaptureSession addOutput:] 无法将输出添加到捕获会话

有问题的代码如下:

    func notificationCenter() {
    NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: UIApplication.willResignActiveNotification , object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(openedAgain), name: UIApplication.didBecomeActiveNotification, object: nil)
}

@objc func openedAgain() {
    setupCamera() //This is your function that contains the setup for your camera.
}

@objc func willResignActive() {
    print("Entered background")
    let inputs = captureSession.inputs
    for oldInput:AVCaptureInput in inputs {
        captureSession.removeInput(oldInput)
    }
}

这里的方法被调用viewdidload

注意:当您返回时,摄像头会话似乎仍在工作,即使出现错误,因为我可以看到摄像头看到的内容,但除了移动摄像头之外我无能为力。

标签: iosswift

解决方案


根据 文档

addOutput:该方法在调用时会抛出异常,并且 canAddOutput(_:) 返回 false。

因此,在添加任何输出之前,您必须canAddOutput通过添加输入进行检查canAddInput

captureSession.stopRunning()关于您在辞职和captureSession.startRunning()活跃时需要使用的问题

NotificationCenter.default.addObserver(self, selector: #selector(stopTheSession), name: UIApplication.applicationDidEnterBackground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(startTheSession), name: UIApplication.applicationWillEnterForeground, object: nil)

推荐阅读