我希望我的应用在另一天发生变化时起作用。
所以,在我的appDelegate中,我放了
func applicationSignificantTimeChange(_ application: UIApplication){
//this one fires
}
并且应该在ViewController中更新其内容:
override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(self.dayChanged(notification:)), name: Notification.Name("significantTimeChangeNotification"), object: nil)
}
和
@objc func dayChanged(notification: NSNotification){
//this one doesn't fire
}
以某种方式,虽然调用了AppDelegate中的func,但观察者似乎对该事件视而不见。
这是语法,还是对机制的简单误解?
您需要为UIApplicationSignificantTimeChangeNotification
添加观察者:
NotificationCenter.default.addObserver(self, selector: #selector(dayChanged), name: UIApplicationSignificantTimeChangeNotification, object: nil)
对于Swift 4.2或更高版本
NotificationCenter.default.addObserver(self, selector: #selector(dayChanged), name: UIApplication.significantTimeChangeNotification, object: nil)
注意:如果要在日期更改时通知您的意图,则可以使用.NSCalendarDayChanged
代替UIApplication.significantTimeChangeNotification
。