UNUserNotificationCenter.getNotificationSettings 中的计时器故障

Timer failure in UNUserNotificationCenter.getNotificationSettings

我正在尝试根据应用程序是否提供推送权限在视图控制器上启动一些计时器,但计时器未触发。谁能给我解释一下这是为什么?

class SomeViewController: UIViewController {

    private var startTime: Date!

    private var countDown: Timer?
    private var timer: Timer?

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        startTime = Date()

        UNUserNotificationCenter.current().getNotificationSettings { settings in
            if settings.authorizationStatus == .denied || settings.authorizationStatus == .notDetermined {
                self.timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(self.manualFunction(_:)), userInfo: nil, repeats: true)
            } else {
                // Wait two seconds, then start the manual check.
                self.countDown = Timer.scheduledTimer(withTimeInterval: 2, repeats: false, block: { (timer) in
                    self.timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(self.manualFunction(_:)), userInfo: nil, repeats: true)
                })
            }
        }
    }

    @objc private func manualFunction(_ timer: Timer) {
        // Some function I want to execute whenever the second timer triggers.
    }

}

viewDidAppear 函数用于包含以下有效的代码:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    startTime = Date()

    self.countDown = Timer.scheduledTimer(withTimeInterval: 2, repeats: false, block: { [weak self] (timer) in
        guard let self = self else { return }
        self.timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(self.manualFunction(_:)), userInfo: nil, repeats: true)
    })
}

我试过制作计时器 weak,我试过在几个地方添加 [unowned self][weak self],但没有成功。有人可以解释这种行为吗?

当调用 getNotificationSettings 方法时,您正在进入后台队列,您应该返回主队列来处理要在主队列中执行的任务。

UNUserNotificationCenter.current().getNotificationSettings { settings in
    DispatchQueue.main.async {
        // Add your tasks here
    }
}