我有图标角标(Badge)编号更新要求。该应用程序跟踪任务。我希望应用程序有一个角标(Badge),显示每天到期的任务数量。角标(Badge)号码需要更新的情况基本上有两种情况:
- 每天午夜。
- 如果添加新任务或删除任务。
我知道如何处理第二种情况。我可以在 applicationResignActive 函数中设置角标(Badge)编号。然而,午夜自动更新对我来说是个骗局。要更新角标(Badge)编号,我需要调用应用程序的函数来计算当天到期的任务。然而,在午夜,应用程序可能处于所有可能的情况:前台、后台和未运行。我怎样才能做到这一点?谢谢。
========================================
为了更清楚地表达我的要求,我希望角标(Badge)编号每天都能正确更新,即使用户一整天或连续几天都没有打开应用程序。另外,我会尝试避免服务器端支持,因为该应用程序到目前为止是一个独立的应用程序。非常感谢您的帮助。
========================================
最终更新:我接受了维塔利的回答。然而,他的回答要求该应用程序每天至少打开一次。否则,事件将不会触发,角标(Badge)编号也无法更新。
此外,就我而言,每次应用程序进入后台事件触发时,我都必须删除现有通知并安排一个新通知,并重新计算最新的角标(Badge)编号。
我仍然有兴趣以某种方式处理应用程序每天都没有打开的情况,如何确保角标(Badge)编号正确。到目前为止,最简单的方法是设置一些服务器并让它定期向应用程序推送通知。
最佳答案
您可以使用UILocalNotification
来实现它:
- 当应用进入后台时,计算最近午夜的确切角标(Badge)计数
- 根据计算出的角标(Badge)计数在最近的午夜安排
UILocalNotification
- 您将在午夜收到通知,并且应用的角标(Badge)计数将会更新
示例代码:
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Calculate nearest midnight or any other date, which you need
NSDate *nearestMidnight = [self nearestMidnight];
// Create and setup local notification
UILocalNotification *notification = [UILocalNotification new];
notification.alertTitle = @"Some title";
notification.alertBody = @"Some message";
notification.fireDate = nearestMidnight;
// Optional set repeat interval, if user didn't launch the app after nearest midnight
notification.repeatInterval = NSCalendarUnitDay;
// Calculate badge count and set it to notification
notification.applicationIconBadgeNumber = [self calculateBadgeCountForDate:nearestMidnight];
[application scheduleLocalNotification:notification];
}
关于ios - 更新 iOS 图标角标(Badge)编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33621105/