Bram
Bram

Reputation: 3264

Timer failure in UNUserNotificationCenter.getNotificationSettings

I'm trying to start some timers on a view controller, based on whether or not the application has provided push permissions, but the timers are not triggering. Can anyone explain to me why that is?

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

}

The viewDidAppear function used to contain the following code that did work:

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

I've tried making the timers weak, I've tried adding [unowned self] and [weak self] in several spots, without a success. Can someone explain this behaviour?

Upvotes: 0

Views: 101

Answers (1)

Frankenstein
Frankenstein

Reputation: 16341

When calling the getNotificationSettings method you're entering the background queue and you should come back to your main queue to handle task that are to be performed in the main queue.

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

Upvotes: 2

Related Questions