I have a NSTimer which should be work when app in foreground but should stop when app goes to background. but if came again to foreground timer is not working. Is there any way to do that?
inbox.m
(viewDidLoad){
myTimer = [NSTimer scheduledTimerWithTimeInterval: 0.60 target: self selector: @selector(saveSlow) userInfo: nil repeats: YES];
if([[NSUserDefaults standardUserDefaults] boolForKey:@"enterBG"]==YES)
{
[myTimer invalidate];
myTimer = nil;
}
....
}
Have you reset the bool value of enterBG
after the app enter foreground? If not, even the timer is generated, it'll be invalidated again later.
Another point, you generated your timer in -viewDidLoad
, generally, the view life loop only invoke it one time. The next time your app enter foreground, it won't be invoked. This might be another reason why your timer won't works again. You can try put it to You need to invoke the code snippet manually.-viewWillAppear:
instead.
And a suggestion, you'd better to use the related notification to handle the timer:
UIApplicationDidEnterBackgroundNotification
UIApplicationWillEnterForegroundNotification