Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS NSNotificationCenter to check whether the app came from background to foreground

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.

like image 468
user3115014 Avatar asked Jul 23 '14 12:07

user3115014


People also ask

How do I know if an app is in the background or foreground iOS?

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.

Which state iOS app is in if app is running in foreground but not receiving user events?

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.

What is the foreground on iOS?

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.


2 Answers

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]; 
like image 181
Nikita Took Avatar answered Sep 19 '22 12:09

Nikita Took


Swift 4.2

NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification             , object: nil) 
like image 40
Andrea Miotto Avatar answered Sep 19 '22 12:09

Andrea Miotto