Search code examples
swiftobservers

How to detect day change in Swift


I want my app to act when there is a change to another day.

So, in my appDelegate, I put

func applicationSignificantTimeChange(_ application: UIApplication){
        //this one fires
    }

and in the ViewController that should update its content I do:

override func viewDidLoad() {
        NotificationCenter.default.addObserver(self, selector: #selector(self.dayChanged(notification:)), name: Notification.Name("significantTimeChangeNotification"), object: nil)

    }

and

@objc func dayChanged(notification: NSNotification){
        //this one doesn't fire
    }

somehow, while the func in AppDelegate is called, the observer seems to be blind for that event.

Is this syntax, or just plain misunderstanding of the mechanism?


Solution

  • You need to add an observer for "UIApplicationSignificantTimeChangeNotification":

    NotificationCenter.default.addObserver(self, selector: #selector(dayChanged), name: UIApplicationSignificantTimeChangeNotification, object: nil)
    

    For Swift 4.2 or later

    NotificationCenter.default.addObserver(self, selector: #selector(dayChanged), name: UIApplication.significantTimeChangeNotification, object: nil)
    

    Note: If your intent is to be notified when the day changes you can use .NSCalendarDayChanged ("NSCalendarDayChangedNotification") instead of UIApplication.significantTimeChangeNotification.

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

    And add the selector method to the view controller where you would like to monitor the day changes:

    @objc func dayChanged(_ notification: Notification) {
        
    }