iOS: How to tell when an app is going to suspend?

11.7k views Asked by At

I want to know when my app is going to be suspend? The state of not being active for a certain amount of time or being terminated by the user. I need this because I need to close a connection a web socket. I want to keep the connection alive while the app is in the background state though.

How do I do this?

Thanks

3

There are 3 answers

7
Nikos M. On BEST ANSWER

In your AppDelegate.m file this method will be called when the user hits the home button and the app will go to the background (here you can keep your connection live, but you should read the apple documentation regarding background tasks, because your connection cannot be live forever if the app remains in the background. There are other ways to keep your app up to date like update on push notification etc):

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

and this method will be called when the app will get terminated (closed completely from multitasking).

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

You can handle your connections within this methods.

4
Keshav On

You can also add Notification observer

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

- (void) receiveSuspendNotification:(NSNotification*)notif
{
}

method will get called and you can perform the required tasks.

0
hippo On

if your app did not register running in background, then when receiving the UIApplicationDidEnterBackgroundNotification your app will be suspended in RAM.