如何覆盖或更新UILocalNotification

时间:2014-04-15 05:15:59

标签: ios objective-c uilocalnotification

我正在使用UILocalNotification对象向我的应用程序发出通知。目前,每次生成事件时,我都会弹出通知。

  notification.alertBody=@"Event Occurs 2";
  notification.alertAction=@"Open";
  [[UIApplication sharedApplication]presentLocalNotificationNow:notification];

但是,由于每次生成新通知时事件都会继续发生。

是否有办法更新通知(如果通知已存在)并创建新通知(如果不存在)。

3 个答案:

答案 0 :(得分:4)

您无法更新已安排的本地通知。但是,你可以取消它并重新安排一个新的。

取消您的本地通知:

UIApplication *app = [UIApplication sharedApplication];
NSArray *eventArray = [app scheduledLocalNotifications];
for (int i=0; i<[eventArray count]; i++)
{
    UILocalNotification* oneEvent = [eventArray objectAtIndex:i];
    NSDictionary *userInfoCurrent = oneEvent.userInfo;
    NSString *uid=[NSString stringWithFormat:@"%@",[userInfoCurrent valueForKey:@"uid"]];
    if ([uid isEqualToString:uidtodelete])
    {
        //Cancelling the specific local notification
        [app cancelLocalNotification:oneEvent];
        //Schedule your new "updated" local notification here.
        break;
    }
}

这将遍历所有计划的本地通知并删除您要删除的本地通知。请注意,您需要为每个通知设置唯一属性以区分其他通知(在上面的示例中,假设userInfo包含唯一的&#34; uid&#34;)。

感谢KingofBliss上面代码how to delete specific local notifications

答案 1 :(得分:1)

无法更新通知,但是如果您附加带有警报密钥的字典:

UILocalNotification *notification = [[UILocalNotification alloc] init];

NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
[userInfo setObject:alarmID forKey:@"AlarmKey"];
// Set some extra info to your alarm
notification.userInfo = userInfo;

然后,您可以检索本地通知,取消它并创建一个包含更新内容的新通知。

+ (UILocalNotification *)existingNotificationWithAlarmID:(NSString *)alarmID
{
    for (UILocalNotification *notification in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
        if ([[notification.userInfo objectForKey:@"AlarmKey"] isEqualToString:alarmID]) {
            return notification;
        }
    }

    return nil;
}

您取消通知如下:

- (void)cleanUpLocalNotificationWithAlarmID:(NSString *)alarmID
{
    UILocalNotification *notification = [self existingNotificationWithAlarmID:alarmID];
    if (notification) {
        [[UIApplication sharedApplication] cancelLocalNotification:notification];
    }
}

答案 2 :(得分:0)

不,无法修改已安排的本地通知。您必须取消通知并再次安排通知。