Ios 快速清晰相机预览层

Ios 快速清晰相机预览层,ios,swift,camera,Ios,Swift,Camera,我有一个在AVCaptureVideoPreviewLayer上显示相机预览的应用程序。 当应用程序转到后台时,会话将停止。问题是,当我再次打开应用程序时,在初始化新会话之前,从我停止该层上的会话时起,会有一个预览。如何在AVCaptureVideoPreviewLayer上清除此预览?在新的会话开始工作之前,我不希望它只包含黑色背景 代码的某些部分如下所示,但并非全部: private var displayVideo = false { didSet { guard

我有一个在AVCaptureVideoPreviewLayer上显示相机预览的应用程序。 当应用程序转到后台时,会话将停止。问题是,当我再次打开应用程序时,在初始化新会话之前,从我停止该层上的会话时起,会有一个预览。如何在AVCaptureVideoPreviewLayer上清除此预览?在新的会话开始工作之前,我不希望它只包含黑色背景

代码的某些部分如下所示,但并非全部:

private var displayVideo = false {
    didSet {
        guard displayVideo != oldValue else { return }
        if displayVideo {
            // Configure video capture session.
            captureSession = {
                guard let captureDevice = self.captureDevice else { return nil }
                let captureSession = AVCaptureSession()
                captureSession.sessionPreset = AVCaptureSessionPresetHigh
                let videoDeviceInput = try! AVCaptureDeviceInput(device: captureDevice)
                guard captureSession.canAddInput(videoDeviceInput) else {
                    print("Warning. Failed to add input to capture session.")
                    return nil
                }
                captureSession.addInput(videoDeviceInput)
                configureVideoDevice()
                return captureSession
            }()
            configureVideoOrientation()
        }
        else { captureSession = nil }
    }
}

private var captureSession: AVCaptureSession? {
    didSet {
        if oldValue != captureSession { oldValue?.stopRunning() }
        cameraPreviewLayer.session = captureSession
        captureSession?.startRunning()
    }
}
private lazy var captureDevice: AVCaptureDevice? = {
    guard let videoDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) else {
        print("Warning. Failed to get capture device.")
        return nil
    }
    return videoDevice
}()
private lazy var cameraPreviewLayer: AVCaptureVideoPreviewLayer = {
    let layer = self.layer as! AVCaptureVideoPreviewLayer
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill
    return layer
}()

为此,当您停止层上的会话时,您可以将nil分配给预览层。在这种情况下,我无法将nil分配给预览层,因为我正在UIView子类中使用self.layer casted to AVCaptureVideoPreviewLayer。还有别的办法吗?我不想仅仅为此添加单独的层。您可以稍后创建新层并添加到层中——以及在您使用相机时……可能这个第三方会帮助您:……检查此项……希望在铸造self.layer之前,您可以更改已停止会话的self.layer的背景色,以显示黑色背景。