I have an app that displays camera preview on AVCaptureVideoPreviewLayer.
When app goes to background session is stopped. The problem is, that when I open the app again, then before new session is initialized, there is sill a preview from the time I stopped the session on the layer. How can I clean this preview on AVCaptureVideoPreviewLayer? I wan't it to contain just black background until new session is working.
Some parts of the code are bellow, but not all of it:
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
}()
Copyright Notice:Content Author:「Damian Dudycz」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/43340608/swift-clear-camera-preview-layer