函数不会在委托方法中调用 - IOS / Swift

时间:2016-02-15 16:14:50

标签: ios swift nstimer capture-output

我正在使用自定义相机开发应用程序,我使用了captureOutput方法(比方说A),这是AVCaptureVideoDataOutputSampleBufferDelegate的委托方法。

我使用了另一个函数(比方说B),其行为类似于javascripts中的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方法时,它工作正常。但在这个特殊方法中,它没有被调用。有人可以给我一个解决方案。任何帮助都将受到高度赞赏。

已编辑:对我的代码无效的原因感到困惑。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

这可能更适合您的目的。它会做你想做的事。

//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
    }

}

答案 1 :(得分:0)

我能够找到一种方法来完成我的工作。但是找不到我以前的代码有什么问题。这就是它的样子

func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {

    let seconds: Int64 = 1 * Int64(NSEC_PER_SEC);

    let time = dispatch_time(DISPATCH_TIME_NOW, seconds);

    dispatch_after(time, dispatch_get_main_queue(), {
        //piece of code i want to run
    });
}