jfisk jfisk - 7 months ago 17
iOS Question

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

I have a view controller that uses an

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?


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


    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];