简体   繁体   中英

NSTimer not stopping after the app goes into background

Until yesterday I was sure, the NSTimer will get stopped after the app goes into background. I'm have a feeling like experiencing some anomally.

My app has update location and play audio background modes. Update location is refreshed every few seconds. But it only happends on one of the app screens. There also is NSTimer refreshing some UI.

I've scheduled it like this:

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];

There is also a method, which content is irrelevant now:

-(void)updateTime
{
//irrelevant content, but the method gets fired even when the app is in background
}

The weird thing is, thah the method, which is only fired by the NSTimer and nowehere else is fired even after the ap go into the background. What is happening here? Is that normal behaviour?

Because you are using background modes with location and audio your app is still alive in background.and so your timers are running.

If you remove background modes with location and audio that you are using and then try the timers wont work.

Its Normal behaviour. Correct me if i'm wrong.

Create your timer as public i mean add it in .h file and access it when your app. enter in backGround Mode

- (void)applicationDidEnterBackground:(UIApplication *)application

By above method and set your timer as inValidate .. its fix.

And if you want to do again start your timer then you can access it by

- (void)applicationWillEnterForeground:(UIApplication *)application 

this method. Here you need to recreate your timer.

You can stop the timer using invalidate the timer.

[self.timer invalidate]; self.timer= nil;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM