iOS NSNotificationCenter to check whether the app came from background to foreground
Solution 1
Have you tried UIApplicationWillEnterForegroundNotification
?
The app also posts a UIApplicationWillEnterForegroundNotification notification shortly before calling applicationWillEnterForeground:
to give interested objects a chance to respond to the transition.
Subscribe to notification:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(yourUpdateMethodGoesHere:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
Implement a code, that need to be called:
- (void) yourUpdateMethodGoesHere:(NSNotification *) note {
// code
}
Don't forget to unsubscribe:
[[NSNotificationCenter defaultCenter] removeObserver:self];
Solution 2
Swift 4.2
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification
, object: nil)
Solution 3
Swift 5
Subscribe to Notification -
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(
self,
selector: #selector(applicationWillEnterForeground(_:)),
name: UIApplication.willEnterForegroundNotification,
object: nil)
}
Remove subscription -
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
Function to be called -
@objc func applicationWillEnterForeground(_ notification: NSNotification) {
self.volumeSlider.value = AVAudioSession.sharedInstance().outputVolume
}
Solution 4
Swift 3 version
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) {
....
}
you can also use NSNotification.Name.UIApplicationDidBecomeActive
Solution 5
Swift 5 use: UIApplication.willEnterForegroundNotification
![user3115014](https://i.stack.imgur.com/Ubfz5.jpg?s=256&g=1)
user3115014
Updated on February 17, 2021Comments
-
user3115014 over 3 years
I have a situation in which i have to intialize an object everytime when it comes from background to foreground and that should be using the NSNotificationCenter not with appdelegate because iam building a static library so there wont be appdelegate with that so please help me in the same.