0

In my Swift 2.3 I had a timer that could run in a seperate thread. I could access the timer by creating an instance of it. Code in Swift 2.3:

public struct Dispatch {
    public typealias Block = () -> ()
}

extension Dispatch {
    public static func timerAsync(queue: dispatch_queue_t = dispatch_get_global_queue(qos_class_main(), 0), interval: Double, block: Block) -> dispatch_source_t {
        let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, UInt64(interval * Double(NSEC_PER_SEC)), 100);
        dispatch_source_set_event_handler(timer, block);
        dispatch_resume(timer);
        return timer;
    }
}

extension dispatch_source_t {
    public func invalidate() -> Self {
        dispatch_source_cancel(self);
        return self;
    }
}

I could start the timer by typing:

timer1 = timerAsync(interval: intervalTime){
    //some code to run every intervalTime
}

and also stop the timer by typing:

timer1.invalidate();

But I can't figure out how to write an equivalent code in Swift 3.0. Any help is appreciated.

Thanks!

Ali M
  • 67
  • 1
  • 8
  • Here's how I do it: https://github.com/mattneub/Programming-iOS-Book-Examples/blob/4c226da779870acfbbaf431c8a18d2701eae0709/bk1ch12p499cancelableTimer/ch12p325NotificationLeaker/CancelableTimer.swift – matt Jan 25 '17 at 04:10
  • @matt thanks that was very useful! – Ali M Feb 01 '17 at 08:20

0 Answers0