0

我正在为我正在开发的应用程序添加本地通知。我只在 2013 年 4 月 30 日纽约/东部时间晚上 11:00 设置了一个通知。我该怎么做?我尝试了多种方法,但没有一种方法能正常工作。这是我目前正在使用的(它不起作用):

- (void)applicationDidEnterBackground:(UIApplication *)application
{
if (![@"1" isEqualToString:[[NSUserDefaults standardUserDefaults]
                            objectForKey:@"setNotify"]]) {
    [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:@"setNotify"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    NSString *str = [NSString stringWithFormat:@"2013-04-23T18:22:00"];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss'"];
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"US/Eastern"]];
    NSDate *dte = [dateFormat dateFromString:str];
    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [cal setTimeZone:[NSTimeZone timeZoneWithName:@"US/Eastern"]];
    UIApplication* app = [UIApplication sharedApplication];
    UILocalNotification* notifyAlarm = [[UILocalNotification alloc]
                                        init];
    if (notifyAlarm)
    {
        notifyAlarm.fireDate = dte;
        notifyAlarm.timeZone = [NSTimeZone timeZoneWithName:@"US/Eastern"];
        notifyAlarm.repeatInterval = 0;
        notifyAlarm.soundName = @"trumpet.m4a";
        notifyAlarm.alertBody = @"Message";
        [app scheduleLocalNotification:notifyAlarm];
    }
}
}
4

2 回答 2

1

我注意到的一件事是,我怀疑您是否打算在日期格式化程序中使用 YYYY。来自 Apple 文档

A common mistake is to use YYYY. yyyy specifies the calendar year whereas
YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar.
In most cases, yyyy and YYYY yield the same number, however they may
be different. Typically you should use the calendar year.

当我更改此代码时,您的代码对我有用并发布了通知。

于 2013-04-23T23:05:35.000 回答
1

试试下面的代码:

NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:30];
[dateComps setMonth:4];
[dateComps setYear:2013];
[dateComps setHour:23];
[dateComps setMinute:0];
[dateComps setSecond:0];

NSDate *itemDate = [calendar dateFromComponents:dateComps];

UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
    return;
localNotif.fireDate = itemDate;
localNotif.timeZone = [NSTimeZone timeZoneWithName:@"US/Eastern"];

localNotif.alertBody = @"Message";
localNotif.repeatInterval = 0;
localNotif.soundName = @"trumpet.m4a";
localNotif.applicationIconBadgeNumber = 1;

[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
于 2013-04-23T22:45:04.110 回答