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.
To detect if an iOS application is in background or foreground we can simply use the UIApplication just like we can use it to detect many other things like battery state, status etc. The shared. application state is an enum of type State, which consists of the following as per apple documentation.
Inactive – The app is running in the foreground, but not receiving events. An iOS app can be placed into an inactive state, for example, when a call or SMS message is received.
Overview. Use foreground transitions to prepare your app's UI to appear onscreen. An app's transition to the foreground is usually in response to a user action. For example, when the user taps the app's icon, the system launches the app and brings it to the foreground.
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];
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification , object: nil)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With