如果数组日期与今天日期相同,则为本地通知

时间:2013-03-14 13:19:13

标签: ios notifications

我有一个类似的数组:

_combinedBirthdates(
"03/05/2013",
"09/22/1986",
"03/02/1990",
"03/02",
"08/22/1989",
"11/02/1990",
"07/08",
"08/31/1990",
"05/13",
"07/11/2007",
"10/07/2010",
"02/20/1987")

如果今天的日期与上面数组中的日期相同,我想要本地通知

我使用以下逻辑进行通知:

NSLog(@" _combinedBirthdates%@",_combinedBirthdates);  
NSDateFormatter *Formatter1 = [[NSDateFormatter alloc] init];
[Formatter1 setDateFormat:@"MM/dd"];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
NSDate *date1 =[NSDate date];
NSString *string =[Formatter1 stringFromDate:date1];
NSDate *todaydate =[Formatter1 dateFromString:string];

for (int i=0;i<_combinedBirthdates.count;i++)
{
    NSDate *date =[Formatter1 dateFromString:[_combinedBirthdates objectAtIndex:i ]];
    if(date == todaydate){
    localNotif.fireDate = date;
    localNotif.alertBody = @"birthdate notification";
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    }

现在我的问题:

  1. 这段代码好吗?
  2. 我是否需要设备来测试此代码,或者我可以在模拟器中测试它?
  3. 何时会出现通知?在凌晨12:00?
  4. 如果申请已关闭,是否会显示通知?
  5. 如果代码不正确,请修改它。

1 个答案:

答案 0 :(得分:2)

  1. 你的代码有些错误,我在这里已经纠正过了。
  2. 是的,我们可以在模拟器中运行它进行测试。
  3. UILocalNotifications将在我们在相应通知上指定的日期触发。在分配通知时,我们会考虑的时间是什么。如果我们没有设定时间,那么设备时间将被考虑用于触发的日期。
  4. 即使应用程序也关闭,本地通知也会触发,但在我们点击操作按钮之前它不会。见这个规范......
  5. 查看修改后的代码....

    NSMutableArray *newBirthDates = [[NSMutableArray alloc] init];;
    for(int i = 0; i < [_combinedBirthdates count]; i++)
    {
        NSString *date = [_combinedBirthdates objectAtIndex:i];
        NSArray *dateComponents = [date componentsSeparatedByString:@"/"];
        if([dateComponents count] == 3)
        {
            [newBirthDates addObject:[NSString stringWithFormat:@"%@/%@",[dateComponents objectAtIndex:0], [dateComponents objectAtIndex:1]]];
        }
        else
        {
            [newBirthDates addObject:date];
        }
    }
    NSDateFormatter *Formatter1 = [[NSDateFormatter alloc] init];
    [Formatter1 setDateFormat:@"MM/dd"];
    NSDate *date1 =[NSDate date];
    NSString *string =[Formatter1 stringFromDate:date1];
    NSDate *todaydate =[Formatter1 dateFromString:string];
    
    for (int i=0;i<newBirthDates.count;i++)
    {
        NSDate *date =[Formatter1 dateFromString:[newBirthDates objectAtIndex:i ]];
        NSComparisonResult result = [date compare:todaydate];
        if(result == NSOrderedSame)
        {
            UILocalNotification *localNotif = [[UILocalNotification alloc] init];
            localNotif.fireDate = date;
            localNotif.alertBody = @"birthdate notification";
            [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
        }
    }