简体   繁体   中英

Keep NSTimer running when app is in background

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!

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 .

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