.NSCalendarDayChanged only observed when app is in foreground

432 Views Asked by At

I have a question about whether an observer for NSCalendarDayChanged can function when the app is in the background. The following code only triggers when 1) the date changes AND 2) the app is subsequently brought to the foreground.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(calendarDayDidChange(notification:)), name: .NSCalendarDayChanged, object: nil)

    }

    @objc func calendarDayDidChange(notification : NSNotification) {
        //Do something
        print("The date has changed. Uploading yesterday's data...")
    }

}
1

There are 1 best solutions below

2
grep On

From the documentation: https://developer.apple.com/documentation/foundation/nsnotification/name/1408062-nscalendardaychanged

If the the device is asleep when the day changes, this notification will be posted on wakeup. Only one notification will be posted on wakeup if the device has been asleep for multiple days. There are no guarantees about the timeliness of when this notification will be received by observers. As such, you should not rely on this notification being posted or received at any precise time.