Ios 使用DispatchSource.makeTimerSource()创建的计时器未启动

Ios 使用DispatchSource.makeTimerSource()创建的计时器未启动,ios,grand-central-dispatch,Ios,Grand Central Dispatch,在以下代码中,我尝试创建一个无限重复的计时器: import Foundation import Dispatch class RepeatingTimer { var timer: DispatchSourceTimer? let queue: DispatchQueue var eventHandler: (() -> Void)? private enum State { case none case suspe

在以下代码中,我尝试创建一个无限重复的计时器:

import Foundation
import Dispatch

class RepeatingTimer {

    var timer: DispatchSourceTimer?
    let queue: DispatchQueue

    var eventHandler: (() -> Void)?

    private enum State {
        case none
        case suspended
        case resumed
    }

    private var state: State = .none

    init() {
        queue = DispatchQueue(label: "serial.queue.1")

        timer = DispatchSource.makeTimerSource(queue: queue)
        timer?.cancel()

        timer?.schedule(deadline: .now() + .seconds(1), repeating: .seconds(1), leeway: .milliseconds(100))

        suspend()

        timer?.setEventHandler { [weak self] in
            print(Date())
        }

        resume()
    }

    deinit {
        timer?.setEventHandler {}
        timer?.cancel()

        resume()
        eventHandler = nil
    }

    func resume() {
        if state == .resumed {
            return
        }
        state = .resumed
        timer?.resume()
    }

    func suspend() {
        if state == .suspended {
            return
        }
        state = .suspended
        timer?.suspend()
    }

}
计时器是从应用程序委托实例化的:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    self.rt = RepeatingTimer()
    return true
}
但是print语句永远不会被调用。我花了相当多的时间调试代码,我不确定需要修改什么才能使代码正常运行。

init()
方法中注释以下几行:

// timer?.cancel()
// suspend()
如果可能,请使用
激活
而不是
恢复

if #available(iOS 10.0, *) {
    timer?.activate()
} else {
    timer?.resume()
}

您没有尝试从Appdelegate调用它。您应该调用视图控制器,因为您的代码不支持在后台运行


如果您在viewDidLoad中调用了它,但它不工作,让我们尝试在ViewDidDisplay中调用它。

这解决了问题吗?@Alexander是的,它在我的Mac上工作正常。对我来说,这个答案应该被接受。