   }
 
   @IBAction func toggleRecording(_ sender: Any) {
-    shouldRecord = recordButton.state == NSOnState
+    switch recordButton.state {
+    case NSOnState:
+      beginRecording()
+    default:
+      endRecording()
+    }
+  }
+
+  func beginRecording() {
+    DispatchQueue.global().async {
+      self.captureSession.startRunning()
+      let url = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Desktop/recording.mov")
+      self.movieFileOutput.startRecording(toOutputFileURL: url, recordingDelegate: self)
+    }
+  }
+
+  func endRecording() {
+    movieFileOutput.stopRecording()
   }
 }
 

import Cocoa

class ViewController: NSViewController {

  var shouldRecord: Bool = false

  @IBOutlet var textField: NSTextField!
  @IBOutlet var label: NSTextField!

    view.wantsLayer = true
    view.layer?.backgroundColor = NSColor.white.cgColor

    captureSession.sessionPreset = AVCaptureSessionPresetHigh
    if let videoCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo),
      let videoCaptureInput = try? AVCaptureDeviceInput(device: videoCaptureDevice),
      captureSession.canAddInput(videoCaptureInput),
      captureSession.canAddOutput(movieFileOutput)
    {
      captureSession.addInput(videoCaptureInput)
      captureSession.addOutput(movieFileOutput)

    } else {
        recordButton.isHidden = true
    }
  }

  override func viewDidAppear() {
