我写了一个应用程序,允许用户在日期选择器上输入日期,然后当他们点击按钮时,它将安排本地通知。唯一的问题是,当我点击按钮时,通知会立即触发。任何帮助深表感谢!这是我的代码:
- (IBAction)scheduleNotifButton:(id)sender {
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *currentDate = [self.datePicker date];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:-3];
NSDate *targetDate = [calendar dateByAddingComponents:dateComponents toDate:currentDate options:0];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = targetDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = @"Event is in 3 days!";
localNotif.alertAction = nil;
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 0;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
答案 0 :(得分:4)
您需要使用[NSCalendar dateByAddingComponents:toDate:options:]
代替:
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *currentDate = [self.datePicker date];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:-3];
NSDate *targetDate = [calendar dateByAddingComponents:dateComponents toDate:currentDate options:0];
[dateComponents release];
...
答案 1 :(得分:1)
如果您正在寻找关于如何稍后安排通知的完整代码(比如说3秒),这里是完整的代码:
注意:如果您在应用程序内部,则不会在屏幕顶部看到一个消息框,可能必须通过UIApplication委托处理。
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *currentDate = [[NSDate alloc] init];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setSecond: 3 ];
NSDate *targetDate = [calendar dateByAddingComponents:dateComponents toDate:currentDate options:0];
localNotification.fireDate = targetDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.alertBody = @"Notified";
localNotification.alertAction = @"Show";
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];