mawnch
mawnch

Reputation: 403

AVFoundation take picture every second SWIFT

I'm trying to use AVFoundation framework to take a picture and analyze it in my app. I want it to take a picture every second automatically, how do I do that?

Here is my current code, right now it takes a picture only when call capturePhoto().

func setupSession() {
  session = AVCaptureSession()
  session.sessionPreset = AVCaptureSessionPresetPhoto

  let camera = AVCaptureDevice
     .defaultDeviceWithMediaType(AVMediaTypeVideo)

  do { input = try AVCaptureDeviceInput(device: camera) } catch { return }

  output = AVCaptureStillImageOutput()
  output.outputSettings = [ AVVideoCodecKey: AVVideoCodecJPEG ]

  guard session.canAddInput(input)
     && session.canAddOutput(output) else { return }

  session.addInput(input)
  session.addOutput(output)

  previewLayer = AVCaptureVideoPreviewLayer(session: session)

  previewLayer!.videoGravity = AVLayerVideoGravityResizeAspect
  previewLayer!.connection?.videoOrientation = .Portrait

  view.layer.addSublayer(previewLayer!)

  session.startRunning()
}

func capturePhoto() {
  guard let connection = output.connectionWithMediaType(AVMediaTypeVideo) else { return }
  connection.videoOrientation = .Portrait

  output.captureStillImageAsynchronouslyFromConnection(connection) { (sampleBuffer, error) in
     guard sampleBuffer != nil && error == nil else { return }

     let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
     guard let image = UIImage(data: imageData) else { return }

     //do stuff with image

  }
}

What should I change?

Upvotes: 1

Views: 2595

Answers (1)

Duncan C
Duncan C

Reputation: 131408

So create an NSTimer that fires once a second, and in that NSTimer's method call capturePhoto:

Create a timer that fires once a second:

var cameraTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, 
  target: self, 
  #selector(timerCalled(_:)), 
  userInfo: nil, 
  repeats: true)

Your timerCalled function might look like this:

func timerCalled(timer: NSTimer) {
  capturePhoto()
}

Upvotes: 1

Related Questions