1
我正在嘗試使用AVFoundation框架拍攝照片並在我的應用中對其進行分析。我希望它能夠每秒自動拍攝一張照片,我該怎麼做?AVFoundation每秒拍攝一張照片SWIFT
這是我現在的代碼,現在只有在調用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
}
}
我應該改變什麼?
我應該創建計時器作爲成員變量並調用viewDidAppear中的timerCalled? – mawnch
是的,使計時器變量成爲一個成員變量,並在viewDidAppear中創建計時器。然後你可以在'viewWillDisappear'中調用'timer.invalidate()'。 –