iOS 在应用程序退出 10 天时创建本地通知

iOS create local notification when app exit with 10 days

我正在创建一个本地通知,时间为 10 天,应用程序退出时 15:30。这是一个代码:

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *now = [NSDate date];
    float day = 10;
    NSDate *newDate = [now dateByAddingTimeInterval:60*60*24*day];

    NSDateComponents *componentsForFireDate = [calendar components:(NSYearCalendarUnit | NSWeekCalendarUnit |  NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate: newDate];

    [componentsForFireDate setHour: 15];
    [componentsForFireDate setMinute:30];
    [componentsForFireDate setSecond:0];
    NSDate *fireDateOfNotification = [calendar dateFromComponents:componentsForFireDate];
    UILocalNotification* localNotification = [[UILocalNotification alloc] init];
    localNotification.fireDate = fireDateOfNotification;
    localNotification.repeatInterval = NSWeekCalendarUnit;
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

当我尝试将 phone 中的日期和时间更改为第二天(现在 + 1)时,它仍然显示通知,第二天,仍然显示。我希望在应用程序退出时每 10 天显示一次本地通知。任何解决此问题的建议?

尝试此代码:您的应用在 10 天通知触发和其他 1 天触发后打开。

 NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *componentsForFireDate = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear) fromDate: [NSDate date]];
componentsForFireDate.day = componentsForFireDate.day + 10;
[componentsForFireDate setHour: 15];
[componentsForFireDate setMinute:30];
[componentsForFireDate setSecond:0];
NSDate *fireDateOfNotification = [calendar dateFromComponents:componentsForFireDate];
NSLog(@"Date: %@",fireDateOfNotification);
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = fireDateOfNotification;
localNotification.alertBody = @"This is local notification!";
localNotification.repeatInterval = NSCalendarUnitDay;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

希望这段代码对您有所帮助。

更改系统时间后,请同时检查模拟器时间。最初它没有更新。

在模拟器设置中,General->language & region->Advanced->Automatica开关会打开模式。 select断断续续。那么你的模拟器时间也会改变