我有一种情况,我必须每次从背景到前景初始化一个对象,并且应该使用NSNotificationCenter而不是appdelegate,因为我建立了一个静态库,因此不会有appdelegate,所以请帮助我在同一个。
答案 0 :(得分:25)
您是否尝试过UIApplicationWillEnterForegroundNotification
?
该应用程序还会在调用applicationWillEnterForeground:
之前不久发布UIApplicationWillEnterForegroundNotification通知,以便为感兴趣的对象提供响应转换的机会。
订阅通知:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(yourUpdateMethodGoesHere:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
实现需要调用的代码:
- (void) yourUpdateMethodGoesHere:(NSNotification *) note {
// code
}
别忘了取消订阅:
[[NSNotificationCenter defaultCenter] removeObserver:self];
答案 1 :(得分:8)
Swift 3版本
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(self,
selector:#selector(applicationWillEnterForeground(_:)),
name:NSNotification.Name.UIApplicationWillEnterForeground,
object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
func applicationWillEnterForeground(_ notification: NSNotification) {
....
}
您也可以使用NSNotification.Name.UIApplicationDidBecomeActive
答案 2 :(得分:5)
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification
, object: nil)
答案 3 :(得分:1)
Swift 3和4版本
NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationWillEnterForeground, object: nil, queue: nil) { notification in
...
}
答案 4 :(得分:1)
Swift 5用途: UIApplication.willEnterForegroundNotification
答案 5 :(得分:0)
迅速4.1
override func viewDidAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(enterForeground), name: Notification.Name.UIApplicationWillEnterForeground, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationWillEnterForeground, object: nil)
}
@objc func enterForeground() {
// Do stuff
}
答案 6 :(得分:0)
快捷键5
订阅通知-
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(
self,
selector: #selector(applicationWillEnterForeground(_:)),
name: UIApplication.willEnterForegroundNotification,
object: nil)
}
删除订阅-
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
要调用的函数-
@objc func applicationWillEnterForeground(_ notification: NSNotification) {
self.volumeSlider.value = AVAudioSession.sharedInstance().outputVolume
}