ViewController:

- (void)viewDidLoad
{
`[super viewDidLoad];`

dateFormatter.dateFormat = @"dd/MM";
timeFormatter.dateFormat = @"HH:mm";
NSString *dateString = [dateFormatter stringFromDate:dateTime];
NSString *timeString = [timeFormatter stringFromDate:dateTime];

if ([dateString isEqual:@"23/06"]) {
    if ([timeString isEqual:@"23:30"]) {
        UILocalNotification *localNotification = [[UILocalNotification alloc] init];
        localNotification.fireDate = dateTime;
        localNotification.alertBody = [NSString stringWithFormat:@"It's 11:30 PM 23th June!"];
        localNotification.soundName = UILocalNotificationDefaultSoundName;
        localNotification.applicationIconBadgeNumber = 1;
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    }
}
}

AppDelegate:
[[UIApplication sharedApplication] scheduledLocalNotifications];

if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){

    [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge| UIUserNotificationTypeSound categories:nil]];
}

如果时间等于字符串和日期,则不会收到通知。
请帮忙!

最佳答案

与此相关的核心问题(除了使用字符串比较日期之外)是在此应用程序中只调用一次viewDidLoad。因为您仅计划在当前日期为11:30时本地通知,所以永远不会调用该通知,因为您还将fireDate设置为相同的确切时间。

关键是,本地通知会在事件发生之前进行安排。实际上,您应该将dateTime设置为所需的计划时间,然后设置本地通知。

例如:

- (void)viewDidLoad {

[super viewDidLoad];

NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear:2016];
[dateComponents setMonth:6];
[dateComponents setDay:23];
[dateComponents setHour:23];
[dateComponents setMinute:30];

dateTime = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];

UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = dateTime;
localNotification.alertBody = [NSString stringWithFormat:@"It's 11:30 PM 23th June!"];
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

根据您上传的代码,您似乎将要从datePicker获取日期,因此最终,您将UILocalNotification部分移至button方法,并使用[datePicker date]作为fireDate。意思是,您可以忽略dateComponents部分。

08-18 14:47