本地通知“didReceiveLocalNotification”调用两次

时间:2010-07-12 09:04:20

标签: iphone ios notifications uilocalnotification

我正在使用以下方式处理本地通知:

- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif

并安排本地通知:

- (void)scheduleNotificationWithInterval:(int)minutesBefore {
    UILocalNotification *localNotif = [[UILocalNotification alloc] init];

    if (localNotif == nil)
        return;

    NSDate *fireDate = [NSDate date];
    localNotif.fireDate = [fireDate dateByAddingTimeInterval:minutesBefore*60];
    localNotif.timeZone = [NSTimeZone defaultTimeZone];
    localNotif.repeatInterval = kCFCalendarUnitMinute;
    localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(@"LocalEvent notification in %i minutes.", nil),minutesBefore];
    localNotif.alertAction = NSLocalizedString(@"View Details", nil);
    localNotif.applicationIconBadgeNumber = 1;

    NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:@"This is dict, you can pass info for your notification",@"info",nil];
    localNotif.userInfo = infoDict;

    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];

    [localNotif release];
    NSLog(@"Event scheduled");
}

收到通知时,会didReceiveLocalNotification:被调用两次。

我做错了吗?

请帮忙。

感谢。

4 个答案:

答案 0 :(得分:27)

我认为模拟器中存在一个已知错误,它会触发委托通知方法两次。它不应该发生在设备上,不管是否与XCode相连。

答案 1 :(得分:14)

我也面临同样的问题,我找到的解决方案是在 didReceiveLocalNotification

中编写此代码
if (state == UIApplicationStateActive) {
    NSLog(@"UIApplicationStateActive"); 
}
else if(state == UIApplicationStateInactive){
    NSLog(@"UIApplicationStateInActive");
}

在这些情况下,我只是编写了我希望我的应用程序在通知,活动模式和非活动模式下执行的代码

答案 2 :(得分:1)

我怀疑该通知正在重新启动,只要它在同一秒内仍然存在。我通过在处理程序中将fireDate设置为nil来修复它:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:notification.alertAction message:notification.alertBody delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];

    notification.fireDate = nil;

}

答案 3 :(得分:1)

我发了同样的话。这是因为在AppDelegate的'didFinishLaunchingWithOptions'中两次调用'registerUserNotificationSettings'。但是,只是删除重复的调用还没有解决问题。我不得不删除应用程序,然后重建。只有这样才能解决双本地通知问题。