我希望我的应用程序在另一天发生变化时起作用。
所以,在我的 appDelegate 中,我把
func applicationSignificantTimeChange(_ application: UIApplication){
//this one fires
}
Run Code Online (Sandbox Code Playgroud)
在应该更新其内容的 ViewController 中,我会这样做:
override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(self.dayChanged(notification:)), name: Notification.Name("significantTimeChangeNotification"), object: nil)
}
Run Code Online (Sandbox Code Playgroud)
和
@objc func dayChanged(notification: NSNotification){
//this one doesn't fire
}
Run Code Online (Sandbox Code Playgroud)
不知何故,当 AppDelegate 中的 func 被调用时,观察者似乎对该事件视而不见。
这是语法,还是只是对机制的简单误解?
您需要为以下对象添加观察者UIApplicationSignificantTimeChangeNotification
:
NotificationCenter.default.addObserver(self, selector: #selector(dayChanged), name: UIApplicationSignificantTimeChangeNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)
对于Swift 4.2 或更高版本
NotificationCenter.default.addObserver(self, selector: #selector(dayChanged), name: UIApplication.significantTimeChangeNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)
注意:如果您的意图是在日期更改时收到通知,您可以使用.NSCalendarDayChanged
代替UIApplication.significantTimeChangeNotification
。
NotificationCenter.default.addObserver(self, selector: #selector(dayChanged), name: .NSCalendarDayChanged, object: nil)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
779 次 |
最近记录: |