2013-04-23 80 views
0

我正在將本地通知添加到正在開發的應用中。我在紐約/東部時間2013年4月30日晚上11點設置一個通知。我將如何做到這一點?我試過多種方法,但沒有一個能夠正常工作。這是我使用的是什麼的時刻(它不工作):爲東部時區的未來日期設置本地通知

- (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]; 
    } 
} 
} 

回答

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]; 
1

有一兩件事我注意到的是,我懷疑你的意思是使用YYYY在你的日期格式化程序中。來自Apple Docs

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. 

當我更改此代碼時,我的工作爲我併發布了通知。

相關問題