objective-ciphoneuilocalnotificationusernotifications

Delete a particular local notification


I am developing an iPhone alarm app based on local notifications.

On deleting an alarm, the related local notification should get cancelled. But how can I determine exactly which object from the array of local notifications is to be cancelled?

I am aware of [[UIApplication sharedApplication] cancelLocalNotification:notification] method but how can I get this 'notification' to cancel it?


Solution

  • You can save a unique value for key in your local notification's userinfo. Get all local notification, loop through the array and delete the particular notification.

    Code as follows,

    OBJ-C:

    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 local notification
            [app cancelLocalNotification:oneEvent];
            break;
        }
    }
    

    SWIFT:

    var app:UIApplication = UIApplication.sharedApplication()
    for oneEvent in app.scheduledLocalNotifications {
        var notification = oneEvent as UILocalNotification
        let userInfoCurrent = notification.userInfo! as [String:AnyObject]
        let uid = userInfoCurrent["uid"]! as String
        if uid == uidtodelete {
            //Cancelling local notification
            app.cancelLocalNotification(notification)
            break;
        }
    }
    

    UserNotification:

    If you use UserNotification (iOS 10+), just follow this steps:

    1. When creating the UserNotification content, add an unique identifier

    2. Remove specific pending notification using removePendingNotificationRequests(withIdentifiers:)

    3. Remove specific delivered notification using removeDeliveredNotifications(withIdentifiers:)

    For more info, UNUserNotificationCenter