【发布时间】:2023-03-19 05:44:01
【问题描述】:
我正在尝试为我的本地通知设置一个有条件的触发时间,但是当我尝试这两种方法时,它并没有失败,但它仍然不起作用。所以,我想知道我是否能够做这样的事情?
注意: startTime 和 endTime 是来自日期选择器的时间。
-(void) TEST {
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:[NSDate date]];
components.hour = 3;
components.minute = (components.minute + 1) % 60;
components.second = 57;
NSDate *fire = [calendar dateFromComponents:components];
UILocalNotification *notif = [[UILocalNotification alloc] init] ;
if (notif == nil)
return;
if (fire < startTime.date) {
notif.fireDate =fire ;
notif.repeatInterval= NSMinuteCalendarUnit ;
notif.alertBody = [NSString stringWithFormat: @"You are missed!"] ;
[[UIApplication sharedApplication] scheduleLocalNotification:notif] ;
}
if (fire > endTime.date) {
notif.fireDate =fire ;
notif.repeatInterval= NSMinuteCalendarUnit ;
notif.alertBody = [NSString stringWithFormat: @"You are missed!"] ;
[[UIApplication sharedApplication] scheduleLocalNotification:notif] ;
}}
或
-(void) TEST {
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:[NSDate date]];
components.hour = 3;
components.minute = (components.minute + 1) % 60;
components.second = 57;
NSDate *fire = [calendar dateFromComponents:components];
UILocalNotification *notif = [[UILocalNotification alloc] init] ;
if (notif == nil)
return;
if (fire > startTime.date & fire < endTime.date) {
[[UIApplication sharedApplication] cancelAllLocalNotifications] ;
}
else {
notif.fireDate =fire ;
notif.repeatInterval= NSMinuteCalendarUnit ;
notif.alertBody = [NSString stringWithFormat: @"You are missed!"] ;
[[UIApplication sharedApplication] scheduleLocalNotification:notif] ;
}}
谢谢
如果不是,最简单的方法是什么?
【问题讨论】:
-
您记录了开火日期吗?如果使用组件中的分钟,则需要在从日历+日期(NSMinuteCalendarUnit)获取组件时加载分钟。
-
是的,我确实记录了它,但它从未进入 if 条件
-
试试
if ([fire timeIntervalSinceDate:startTime.date] >= 0) // fire is before start。 -
@relikd 谢谢,但还是不行! ://
-
@Bonnie 你的答案都不起作用,我想没有解决方案可以解决这样的事情,因为无论如何我都找不到在特定时间执行通知取消的背景。 但是,您应该得到 100 分的辛勤工作。谢谢。
标签: iphone ios objective-c cocoa-touch uilocalnotification