ios - 当应用程序在后台时保持 NSTimer 运行

标签 ios nstimer multitasking nsthread

我希望有一位专家可以帮助我解决这个问题:

我在 google 上搜索了几个小时,但找不到任何信息是否有任何方法可以在应用程序在后台运行时保持正在运行的 NSTimer 处于事件状态?

问题场景是我需要在按钮单击时设置倒计时器。剩余时间显示 (02:34:45) 作为按钮标题。当应用程序进入后台或挂起时,我的计时器如何继续运行。请帮助我如何保持闹钟的剩余时间,为闹钟选择的值是多少(例如 2 小时,3 分钟)

感谢您的帮助!

最佳答案

如果您将其用于闹钟,最好的选择是使用本地通知。这样您就不需要使用任何后台处理模式。

当您的应用即将进入后台时(在应用委托(delegate)上的 applicationWillResignActiveapplicationDidEnterBackground 中),获取计时器还剩多少时间。然后在未来安排一个本地通知:

NSTimeInterval timeUntilNotification = ...

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

[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];

当您的应用再次激活时,请确保使用 cancelAllLocalNotifications 取消所有通知。

关于ios - 当应用程序在后台时保持 NSTimer 运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10579597/

相关文章:

ios - NSTimer 内存泄漏(CFArray?)

linux - 如何通过为每个 Linux 内核启动一个任务来(简单地)与 Linux shell 并行化?

ios - SpriteKit 游戏中的多任务问题

ios - 在 Parse 中更新用户电子邮件

objective-c - 使用 NSPredicate 搜索带数组的数组

ios - 如果 Facebook 访问 token 过期,会生成新的 Facebook 访问 token 吗?

iphone - iPhone:4分钟后,循环音频停止

ios - 使实例化的 NSTimers 无效

iphone - 为什么device.multitaskingSupported在某些设备上不起作用?

ios - 在 iOS 中获取 wifi 路由器类型