繁体   English   中英

如何每隔几秒从委托中连续执行一个方法?

[英]How to perform a method in a continuous method from a delegate every few seconds?

我想使用AVCaptureVideoDataOutputSampleBufferDelegate协议执行一些操作。 但是由于它以(我认为)每秒 30 帧的速度捕获每一帧,因此它在 1 秒内执行该方法 30 次,我不希望这样。 我想做的只是执行一次让我们说每 1 秒一次的方法。 到目前为止,我的代码如下所示:

func captureOutput(_ output: AVCaptureOutput,
                   didOutput sampleBuffer: CMSampleBuffer,
                   from connection: AVCaptureConnection) {
    // ... perform something
    // ... wait for a second
    // ... perform it again
    // ... wait for another second
    // ... and so on
}

我怎样才能做到这一点?

您可以为此使用定时器。

Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
    let randomNumber = Int.random(in: 1...20)
    print("Number: \(randomNumber)")

    if randomNumber == 10 {
        timer.invalidate()
    }
}

您可以添加一个计数器并且仅每n步执行您的代码,例如,当您希望每 30 次调用 function 时执行您的代码:

var counter: Int = 0

...

func captureOutput(_ output: AVCaptureOutput,
                   didOutput sampleBuffer: CMSampleBuffer,
                   from connection: AVCaptureConnection) {
    if counter%30 == 0 {
        // perform your code
    }
    counter += 1
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM