Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to detect when the app is entering the background for my view?

Tags:

ios

nstimer

I have a view controller that uses an NSTimer to execute some code.

What's the best way to detect when the app is going to the background so I can pause the timer?

like image 397
jfisk Avatar asked Jan 25 '12 23:01

jfisk


People also ask

How do you know if an app moves to the background or foreground?

The onPause() and onResume() methods are called when the application is brought to the background and into the foreground again. However, they are also called when the application is started for the first time and before it is killed. You can read more in Activity.

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.


1 Answers

You can have any class interested in when the app goes into the background receive notifications. This is a good alternative to coupling these classes with the AppDelegate.

When initializing said classes:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillTerminate:) name:UIApplicationWillTerminateNotification object:nil]; 

Responding to the notifications

-(void)appWillResignActive:(NSNotification*)note {  } -(void)appWillTerminate:(NSNotification*)note {     [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];     [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];  } 
like image 67
Jesse Black Avatar answered Oct 26 '22 18:10

Jesse Black