2

I hope there's an expert out there who can help me with this:

I googled it for hours, but could not find any information if there is any way to keep a running NSTimer active when the app is running in the background ?

The problem scenario is I need to set a countdown timer on button click. Time left is shown (02:34:45) as title of button. how do my timer is keep on running when application enters into background or it is suspended . Please help me how i can maintain the time left for alarm, what are the values selected for alarm ( like 2 hours , 3 minutes )

Thanks for any help!

Gaurav
  • 1,068
  • 9
  • 15
  • I think there is something about background execution out there... However, I think that it would be better if you save the datetime in the applicationWillResignActive: app. delegate's method and then recalculate the remaining time in applicationDidBecomeActive: method. Good luck! ;) – Ricard Pérez del Campo May 14 '12 at 08:18
  • Thanks man.. I think It will work :) . Do u think its the only solution or we can dig for other alternates.. like background tread.. or so – Gaurav May 14 '12 at 08:32

1 Answers1

4

If you're using it for an alarm, your best bet is to use local notifications. That way you won't need to use any of the background processing modes.

When your app is about to enter the background (in applicationWillResignActive or applicationDidEnterBackground on your app delegate), get how much time is left on your timer. Then schedule a local notification for that far in the future:

NSTimeInterval timeUntilNotification = ...

UILocalNotification *localNotif = [[UILocalNotification alloc] init];
localNotif.fireDate = [[NSDate date] dateByAddingTimeInterval:secondsUntilNotification];
localNotif.soundName = UILocalNotificationDefaultSoundName;

[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];

When your app becomes active again, make sure to cancel all your notifications with cancelAllLocalNotifications.

Amy Worrall
  • 16,250
  • 3
  • 42
  • 65