title: Capturing Video with Swift using AVCaptureVideoDataOutput or AVCaptureMovieFileOutput
body: <p>I need some guidance on how to capture video without having to use an <em>UIImagePicker</em>. The video needs to start and stop on a button click and then this data be saved to the <em>NSDocumentDirectory</em>. I am new to swift so any help will be useful.</p>
  
  <p>The section of code that I need help with is starting and stopping a video session and turning that to data. I created a picture taking version that runs <strong>captureStillImageAsynchronouslyFromConnection</strong> and saves this data to the <em>NSDocumentDirectory</em>. I have set up a video capturing session and have the code ready to save data but do not know how to get the data from the session.</p>
  
  <pre><code>var previewLayer : AVCaptureVideoPreviewLayer?
  var captureDevice : AVCaptureDevice?
  var videoCaptureOutput = AVCaptureVideoDataOutput()
  
  let captureSession = AVCaptureSession()
  
  override func viewDidLoad() {
      super.viewDidLoad()
  
      captureSession.sessionPreset = AVCaptureSessionPreset640x480
      let devices = AVCaptureDevice.devices()
  
      for device in devices {
          if (device.hasMediaType(AVMediaTypeVideo)) {
              if device.position == AVCaptureDevicePosition.Back {
                  captureDevice = device as? AVCaptureDevice
                  if captureDevice != nil {
                      beginSession()
                  }
              }   
          }
      }
  }
  
  func beginSession() {
      var err : NSError? = nil
      captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &amp;err))
  
      if err != nil {
          println("Error: \(err?.localizedDescription)")
      }
  
      videoCaptureOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey:kCVPixelFormatType_32BGRA]
      videoCaptureOutput.alwaysDiscardsLateVideoFrames = true
  
      captureSession.addOutput(videoCaptureOutput)
  
      previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
      self.view.layer.addSublayer(previewLayer)
      previewLayer?.frame = CGRectMake(0, 0, screenWidth, screenHeight)
      captureSession.startRunning()
  
      var startVideoBtn = UIButton(frame: CGRectMake(0, screenHeight/2, screenWidth, screenHeight/2))
          startVideoBtn.addTarget(self, action: "startVideo", forControlEvents: UIControlEvents.TouchUpInside)
          self.view.addSubview(startVideoBtn)
  
      var stopVideoBtn = UIButton(frame: CGRectMake(0, 0, screenWidth, screenHeight/2))
          stopVideoBtn.addTarget(self, action: "stopVideo", forControlEvents: UIControlEvents.TouchUpInside)
          self.view.addSubview(stopVideoBtn)
  }
  </code></pre>
  
  <p>I can supply more code or explanation if needed.</p>