gpt4 book ai didi

ios - 如果应用已打开,则不发送每日本地通知

转载 作者:行者123 更新时间:2023-12-01 18:51:49 25 4
gpt4 key购买 nike

我每天都在同一时间发送Local Notification

我想知道是否存在一种方法,如果用户当天已打开应用程序,是否不发送通知?

这是我用来检查是否允许通知然后发送通知的代码:

- (void)viewDidLoad {
[super viewDidLoad];

UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];

// before we create any new ones, cancel all existing notifications
[[UIApplication sharedApplication]cancelAllLocalNotifications];

if ([[[UIApplication sharedApplication] currentUserNotificationSettings] types] != UIUserNotificationTypeNone) {

UILocalNotification* localNotification = [[UILocalNotification alloc] init];

NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comp = [cal components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:[NSDate date]];
comp.hour = 19; // 19 = 7PM
comp.minute = 45; // 7:45 PM
comp.second = 01; // 7:45:01 PM

localNotification.fireDate = [cal dateFromComponents:comp];
localNotification.alertBody = @"Local Notification in iOS8";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSCalendarUnitDay;

// this will schedule the notification to fire at the fire date
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
// this will fire the notification right away, it will still also fire at the date we set
[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];

}
}

编辑:这是我尝试根据以下答案实现方法建议的代码?我显然在这里没有得到什么:/
- (void)isDateLowerThanToday {
NSDate *now = [NSDate date];
int daysToAdd = -1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
NSLog(@"NewDate1 = %@", newDate1);
}

最佳答案

您可以在 NSUserDefaults 上存储上次发送通知的日期。然后,当应用打开时,您将检查此值,如果它为null或小于今天,则发送通知并使用当前日期更新NSUserDefaults上的值。

这样的事情应该可以解决问题

NSString *key = @"LAST_NOTIFICATION_SENT_DATE";
NSDate *date = [[NSUserDefaults standardUserDefaults] objectForKey:key];

// You have to implement isDateLowerThanToday
if (!date || [self isDateLowerThanToday:date]) {
[self sendNotification];
date = [NSDate date];
[[NUserDefaults standardUserDefaults] setObject:date forKey:key];
}

在这里,您有 isDateLowerThanToday实现
-(bool)isDateLowerThanToday:(NSDate *)date {
NSDate * now = [NSDate date];
NSComparisonResult result = [now compare:date];

return result == NSOrderedDescending;
}

关于ios - 如果应用已打开,则不发送每日本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30629940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com