I am trying to get a preview of my video device in a custom view. But all I get is an empty window. I see that I have no problem accessing my camera. As soon as the app fires up i see my logitech cameras led turn on. I assume my problem is adding the the preview layer as a sublayer.
Here is my simple code:
import Cocoa
import AVFoundation
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var video: NSView!
@IBOutlet weak var window: NSWindow!
let captureSession = AVCaptureSession()
var captureDevice : AVCaptureDevice?
var previewLayer : AVCaptureVideoPreviewLayer?
func applicationDidFinishLaunching(aNotification: NSNotification) {
captureSession.sessionPreset = AVCaptureSessionPresetLow
let devices = AVCaptureDevice.devices()
for device in devices {
if (device.hasMediaType(AVMediaTypeVideo)) {
captureDevice = device as? AVCaptureDevice
println(captureDevice)
}
}
if captureDevice != nil {
beginSession()
}
}
func beginSession() {
println("begin")
var err : NSError? = nil
captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err))
if err != nil {
println("error: \(err?.localizedDescription)")
}
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer!.frame = self.video.bounds
previewLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill
self.video.layer?.addSublayer(previewLayer)
captureSession.startRunning()
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
Solved it.. At Interface Builder, I needed to add a custom view in core animation.