每日午夜更新图标徽章



我正在制作一个应用程序,显示两个人在恋爱中的天数。我想在应用程序图标徽章上显示天数。我知道如何做到这一点,一旦用户离开应用程序,但我想每天更新图标徽章,即使应用程序没有打开或在后台运行,所以用户知道的天数,而不必甚至打开应用程序。"BeenTogether"是一个类似的应用程序,正在做同样的事情,所以我相信这是可能的。我该怎么做呢?

我相信这个问题已经被问过无数次了,但答案仍然是否定的。有很多近似的方法,但都有缺点。

  • 静音推送通知。当然,这意味着你需要知道他们的时区,他们需要有网络连接。
  • 后台取回。这是"定期"运行的,所以你不能在正好午夜更新徽章,但它通常会非常接近。

您可以通过本地通知实现相同的功能。我猜他们开始约会的时候你就开始约会了。你可以每天用本地通知更新徽章计数。

我不确定每个人都理解我的问题,因为事实证明,每天午夜增加一个图标徽章是可能的,而不必安排64个通知。解决方案非常简单:

//Set a random date (only the time matters because it is repeated everyday), but make sure that the time is at midnight!!
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear:2015];
[dateComponents setMonth:1];
[dateComponents setDay:1];
[dateComponents setHour:0];
[dateComponents setMinute:0];
//Create an NSDate from the date components
NSCalendar *calendar = [[NSCalendar alloc]  initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *configuredDate = [calendar dateFromComponents:dateComponents];
//Schedule a local notification, set the repeatInterval to daily
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = configuredDate;
localNotification.alertBody = nil;
localNotification.alertAction = nil;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSCalendarUnitDay;
//Add one to the icon badge number
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

最新更新