objective-c - UILocalNotification 立即触发,而不是在预定时间触发

标签 objective-c iphone uilocalnotification

我有一个对象,它将时间作为 NSString 存储在 NSArray 中。我选择了 NSString,因为我最终会显示很多内容,而不是 NSDate。我正在尝试为其设置 UILocalNotification。我所做的是:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone systemTimeZone];
dateFormatter.dateFormat = @"h:mm a";

for (NSString *s in _times) {
    NSDate *date = [dateFormatter dateFromString:s];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit)
                                                   fromDate:date];
    NSDateComponents *timeComponents = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:date];
    NSDateComponents *dateComps = [[NSDateComponents alloc] init];
    [dateComps setDay:[dateComponents day]];
    [dateComps setMonth:[dateComponents month]];
    [dateComps setYear:[dateComponents year]];
    [dateComps setHour:[timeComponents hour]];
    [dateComps setMinute:[timeComponents minute]];

    NSDate *itemDate = [calendar dateFromComponents:dateComps];

    NSLog(@"%@", [dateFormatter stringFromDate:itemDate]);
    UILocalNotification *note = [[UILocalNotification alloc] init];
    note.alertAction = thePill.name;
    note.alertBody = thePill.note;
    note.fireDate = itemDate;
    note.timeZone = [[NSCalendar currentCalendar] timeZone];

    if (note.fireDate == nil) {
        NSLog(@"nil firedate");
    }

//        note.repeatInterval = NSDayCalendarUnit;

    NSData *data = [self archivePill:thePill];
    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:data forKey:PILL_NOTIFICATION];
    note.userInfo = infoDict;

    [[UIApplication sharedApplication] scheduleLocalNotification:note];
}

当我 NSLog 记录 itemDate 时间时,这就是我想要的。在该方法结束时,本地通知会立即触发。我不知道为什么,因为我的日期是正确的时间,而且我想我只是将 fireDate 设置为该日期?谢谢。

最佳答案

// Fire notification immediately after 1 sec 
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
localNotification.alertBody = @"Your alert message";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

关于objective-c - UILocalNotification 立即触发,而不是在预定时间触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10060578/

相关文章:

ios - 如何在特定时间触发后重复本地通知

iphone - UIButton 选择颜色

iOS 应用程序在最后一行 prepareForSegue 代码处终止。不能踏进去

ios - 将 Sprite 添加到其他 Sprite 位置

iphone - UITableView 如何一次显示两个不同的数组?

ios - 如何以编程方式断开 TCP/IP 套接字连接?

ios - 制作线程化的 NSURLConnections

objective-c - 在特定时间执行选择器

ios - 通知中的应用程序图标出现红色图标

ios - 在 iOS 中的特定时间启动本地通知