如何从日期数组创建ios LocalNotification?

时间:2014-05-14 12:09:22

标签: ios uilocalnotification

我有一系列日期

NSArray *datesArray=[NSArray arrayWithObjects: @"2014-09-14 00:00:00",@"2014-08-21 07:12:36",@"2014-08-14 00:00:00",@"2014-07-14 00:00:00",@"2014-06-14 00:00:00",@"2015-01-01 10:00:00",@"2014-06-14 00:00:00",@"2014-05-14 11:24:15", nil];

现在我想在数组中可用日期前一天开火 如何实现呢?

我正在尝试这个

    NSDateFormatter *Formatter1 = [[NSDateFormatter alloc] init];
    [Formatter1 setLocale:[[NSLocale alloc] initWithLocaleIdentifier:NSLocaleIdentifier]];
    [Formatter1 setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    [Formatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    NSDate *date1 =[NSDate date];
    NSString *string =[Formatter1 stringFromDate:date1];
    NSLog(@"sring %@",string);
    NSDate *todaydate =[Formatter1 dateFromString:string];
    NSLog(@"2day date is %@",todaydate);

for (int i=0;i<datesArray.count;i++)
{
    NSDate *_date =[Formatter1 dateFromString:[datesArray objectAtIndex:i ]];
    NSLog(@"date is %@",_date);
    if(_date == todaydate){
        localNotif.fireDate = _date;
        localNotif.alertBody = @"festival";
        localNotif.alertAction=@"Show me";
        localNotif.applicationIconBadgeNumber = 1;
        localNotif.soundName = UILocalNotificationDefaultSoundName;

        [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    }

1 个答案:

答案 0 :(得分:2)

您可以使用NSCalendar功能减去一天,特别是dateByAddingComponents

NSArray *datesArray = @[@"2014-09-14 00:00:00",@"2014-08-21 07:12:36",@"2014-08-14 00:00:00",@"2014-07-14 00:00:00",@"2014-06-14 00:00:00",@"2015-01-01 10:00:00",@"2014-06-14 00:00:00",@"2014-05-14 11:24:15"];

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:-1];

NSDateFormatter *Formatter1 = [[NSDateFormatter alloc] init];
[Formatter1 setLocale:[[NSLocale alloc] initWithLocaleIdentifier:NSLocaleIdentifier]];
[Formatter1 setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[Formatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

[datesArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    localNotif.fireDate = [calendar dateByAddingComponents:dateComponents toDate:[Formatter1 dateFromString:obj] options:0];
    localNotif.alertBody = @"festival";
    localNotif.alertAction = @"Show me";
    localNotif.applicationIconBadgeNumber = 1;
    localNotif.soundName = UILocalNotificationDefaultSoundName;
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}];

w ^