我正在开发一个带有自定义相机的应用程序,并且我使用了 captureOutput 方法(比方说 A),它是 AVCaptureVideoDataOutputSampleBufferDelegate 的委托(delegate)方法。
我使用了另一个函数(比方说 B),其行为类似于 javascript 中的 setTimeout。
当我在 A 内部调用 B 时,它不会被调用。
这是我的代码
func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
setTimeout(1) { () -> Void in
//piece of code i want to run
}
}
func setTimeout(delay:NSTimeInterval, block:()->Void) -> NSTimer {
return NSTimer.scheduledTimerWithTimeInterval(delay, target: NSBlockOperation(block: block), selector: "main", userInfo: nil, repeats: false);
}
当我在 viewDidLoad() 中调用 setTimeout 方法时,它工作正常。但在这个特定的方法中它没有被调用。有人可以给我一个解决方案吗?任何帮助将不胜感激。
编辑:对我的代码无法工作的原因感到困惑。有什么想法吗?
最佳答案
这可能更适合您的目的。它会完成您想要做的事情。
//From https://gist.github.com/natecook1000/b0285b518576b22c4dc8 by natecook1000
extension NSTimer {
/**
Runs a closure after a specified time
- parameter delay: The time before the `handler` is called
- parameter handler: What happens after `delay` has passed
- returns: The NSTimer
*/
static public func schedule(delay delay: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
let fireDate = delay + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
return timer
}
/**
Runs a closure after a specified time, forever
- parameter interval: The time before the `handler` is called
- parameter handler: What happens after `delay` has passed
- returns: The NSTimer
*/
static func schedule(repeatInterval interval: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
let fireDate = interval + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, interval, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
return timer
}
}
关于ios - 函数未在委托(delegate)方法内调用 - IOS/Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35414058/