user1007895
user1007895

Reputation: 3975

iPhone Application Background Timeout

I would like my iPhone app to terminate after being in the background for 5 minutes. What is the best way to do this?

Upvotes: 1

Views: 3119

Answers (4)

Andrew Zimmer
Andrew Zimmer

Reputation: 3191

I'd say Thomas is right. You should be able to do this easily using User Defaults. In your delegate you'll just need to do some testing..

//See how much time has passed when the app is opened
- (void)applicationWillEnterForeground:(UIApplication *)application {
      NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
      NSDate *lastUsed = (NSDate*)[userDefaults objectForKey:@"LAST_USED"];
      NSDate *now = [NSDate date];
      NSTimeInterval interval = [now timeIntervalSinceDate:lastUsed];

      if(interval/60 > 5) { //more than 5 min have passed
           //Force a login
      } else {
           //Continue your session
      }
}

And make sure to save your time when the app is closed.

//Save the current time when the app is closed
- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[NSDate date] forKey:@"LAST_USED"];
    [userDefaults synchronize];
}

Upvotes: 0

Tommaso
Tommaso

Reputation: 155

You can try to do this

LaData=[[NSDate alloc] initWithTimeIntervalSinceNow:300];
[[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:LaData];

NSDate *ladatadiarrivo=[NSDate dateWithTimeIntervalSinceNow:300];
while ([ladatadiarrivo timeIntervalSinceNow]>0) {
    if (ExitFlag) return; //To exit when reactivate              

}
//Code to Kill Application

Upvotes: 0

XJones
XJones

Reputation: 21967

It's bad practice to terminate your app explicitly in code. Your app isn't active when in the background in any case, you can only do anything when a piece of your code is running (registered background operations).

If you want your app to stop background operations or to reset itself to a known state if it has been in the background for a specific interval (e.g. 5 minutes) store a timestamp when the app enters the background and react to the timestamp appropriately in any operations and when the app returns to the foreground.

Upvotes: 2

Thomas Clayson
Thomas Clayson

Reputation: 29935

I don't think that this is possible. What is the point of doing it?

The best fix (without knowing what you're trying to do) is to store the current timestamp when your app goes into the background and then when it comes back into the foreground see if 5 mins have passed and reset the data or something.

Upvotes: 5

Related Questions