How to access Mac default camera using swift xcode
In your code the
self.view.layer?.addSublayer(previewLayer)
will not be executed since self.view.layer
is nil
so that won't be executed.
Alas, this does not seem to be only issue since even when adding a layer the camera does not start working. You will likely have to dig into this:
https://developer.apple.com/library/mac/samplecode/AVRecorder/Introduction/Intro.html
Be sure to check that your view has a Core Animation Layer in IB:
Working code in swift 5.
import Cocoa
import AVFoundation
class SomwViewController: NSViewController {
@IBOutlet private var cameraView: NSView?
let session: AVCaptureSession = AVCaptureSession()
override func viewDidLoad() {
super.viewDidLoad()
cameraView?.wantsLayer = true
cameraView?.layer?.backgroundColor = NSColor.black.cgColor
session.sessionPreset = AVCaptureSession.Preset.low
let input: AVCaptureInput = try! AVCaptureDeviceInput(device: AVCaptureDevice.default(for: .video)!)
session.addInput(input)
let previewLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
previewLayer.frame = cameraView!.bounds
previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
cameraView?.layer?.addSublayer(previewLayer)
}
override func viewDidAppear() {
session.startRunning()
}
override func viewDidDisappear() {
session.stopRunning()
}
}
You should definitely not use force unwraps, it's just an example.