iOS每日本地推送通知 [英] iOS Daily Local Push Notifications
问题描述
我希望每天在 9:00 AM 执行 UILocalNotification
,只要应用程序处于打开状态。我发现的最接近的是:
I want to execute a UILocalNotification
at 9:00 AM every day, forever, as long as the app is open. The closest thing I've found is this:
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [[NSDate date] dateByAddingTimeInterval:60*60*24];
notification.alertBody = @"It's been 24 hours.";
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
但是,此代码只执行 UILocalNotification
一次在24小时内,而不是在指定时间。我一直在考虑以某种方式利用 NSDate
,但一直没有。
However, this code only executes a UILocalNotification
once in 24 hours, not at a specified time. I've been looking into utilizing NSDate
somehow, but have been getting no where.
代码将执行在应用程序中的
方法。如果有人打开应用程序并将其置于上午8:59 的后台,则 AppDelegate
中的didFinishLaunchingWithOptions UILocalNotification
仍将在 9处执行: 00 AM 。
The code will be executing in the AppDelegate
in the application didFinishLaunchingWithOptions
method. If someone were to open the application and place it in the background at 8:59 AM, the UILocalNotification
would still execute at 9:00 AM.
NSDateComponent
将无法使用此功能,因为我必须申报年,月和日,但我想每天执行此 UILocalNotification
而无需编辑代码。
An NSDateComponent
won't work with this because I would have to declare a year, month, and day, but I want to execute this UILocalNotification
every day without having to edit the code.
推荐答案
您需要找到9点发生的NEXT时间,并在当时设置当地通知:
You need to find the NEXT time that 9am occurs, and set the local notification to fire at that time:
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
[components setHour:9];
// Gives us today's date but at 9am
NSDate *next9am = [calendar dateFromComponents:components];
if ([next9am timeIntervalSinceNow] < 0) {
// If today's 9am already occurred, add 24hours to get to tomorrow's
next9am = [next9am dateByAddingTimeInterval:60*60*24];
}
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = next9am;
notification.alertBody = @"It's been 24 hours.";
// Set a repeat interval to daily
notification.repeatInterval = NSDayCalendarUnit;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
这篇关于iOS每日本地推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!