I am trying forever to take a photo programmatically on iOS using Swift. However, the typical methods like:
let renderer = UIGraphicsImageRenderer(size: view.bounds.size)
let image = renderer.image { ctx in
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
}
UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil)
don't work. They take a photo of the everything, but not the live video (using the camera) in the background. Apparently, these methods don't include a live video from the camera in screenshots for security/permissions reasons [the live camera in the screenshot is all white], but there are workarounds. I know there is this answer: Is it possible to render AVCaptureVideoPreviewLayer in a graphics context? but it is written in all Objective-C which I can't read or use, and I'm not sure how it works. Also, there have been suggestions to use Metal, but I haven't found a Swift tutorial for that either.
Can someone please show me (in detail) some Swift code on how to take a screenshot including a photo of the live video on screen. I'm sure this will help all other Swift users too.
Thank you
Edit: Live video Code
let captureDevice = AVCaptureDevice.default(for: AVMediaType.video)
do {
let input = try AVCaptureDeviceInput(device: captureDevice!)
captureSession = AVCaptureSession()
captureSession?.addInput(input)
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
videoPreviewLayer?.frame = view.layer.bounds
previewView.layer.addSublayer(videoPreviewLayer!)
captureSession?.startRunning()
let dataOutPut = AVCaptureVideoDataOutput()
dataOutPut.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue"))
captureSession?.addOutput(dataOutPut)
} catch {
print(error)
}