首页 > 解决方案 > 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]有人可以解释这种行为吗?

标签: swifttimerpermissionsunusernotificationcenter

解决方案


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

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

推荐阅读