我有一个情况,在后台返回前台时需要每次初始化一个对象,而且应该使用NSNotificationCenter而不是AppDelegate,因为我正在构建一个静态库,因此没有AppDelegate,请在此方面帮助我。
我有一个情况,在后台返回前台时需要每次初始化一个对象,而且应该使用NSNotificationCenter而不是AppDelegate,因为我正在构建一个静态库,因此没有AppDelegate,请在此方面帮助我。
你尝试过UIApplicationWillEnterForegroundNotification
吗?
在调用applicationWillEnterForeground:
之前,该应用还会发布一个 UIApplicationWillEnterForegroundNotification 通知,以便给感兴趣的对象一个响应转换的机会。
订阅通知:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(yourUpdateMethodGoesHere:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
实现一个需要被调用的代码:
- (void) yourUpdateMethodGoesHere:(NSNotification *) note {
// code
}
别忘了取消订阅:
[[NSNotificationCenter defaultCenter] removeObserver:self];
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification
, object: nil)
Swift 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
}
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
Swift 5使用:
UIApplication.willEnterForegroundNotification
Swift 5
override func viewDidAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(appMovedToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: UIApplication.willEnterForegroundNotification.rawValue), object: nil)
}
@objc func appMovedToForeground() {
// Do stuff
}
Swift 3和4版本
NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationWillEnterForeground, object: nil, queue: nil) { notification in
...
}