Question

I am new in ios.I am doing a app where i have to count time in background but my problem is time do not stop in foreground. Please tell me how to stop background timer in foreground? Thnx in advnce.

Was it helpful?

Solution

To stop timer somewhere in the same class:

- (void)applicationWillEnterForeground:(UIApplication *)application
{

[Timer invalidate];
    Timer = nil;
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    NSLog(@"Background process is Start(EnterBackground)!");
    __block UIBackgroundTaskIdentifier bgTask ;
    UIApplication  *app = [UIApplication sharedApplication];
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
    Timer = [NSTimer scheduledTimerWithTimeInterval:4.0f target:self  selector:@selector(process)  userInfo:nil repeats:YES];
}

OTHER TIPS

Generally, don't use a timer. Use an NSDate to store the start time you're interested in (such as the app going to the background) and then later compare that date to [NSDate date] (i.e. the current date) to see how much time has passed.

There is really no good reason to run a timer while the app is in the background.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top