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.

Était-ce utile?

La 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];
}

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top