티스토리 뷰

You may want to remove one single notification on Notification Center programmatically.

But if the notification is already shown,

it shouldn’t be removed from notification center before user did something.

However, there is a trick to remove it.

At first I’m gonna show you how to remove a UILocalNotification from notification center.

When the notification is already shown on Notification Center, you cannot get that notification with this property.

@property(nonatomic,copy) NSArray *scheduledLocalNotifications;

This property contains notifications which are not shown yet.

That means, you cannot pass notification to call this function

- (void)cancelLocalNotification:(UILocalNotification *)notification;

Therefore you can’t find the notification to remove it from notification center.

OK, now we know that we have to store our LocalNotification Object somewhere and use it to call 

“cancelLocalNotification:”.

Make a new LocalNotification and set same properties doesn’t help you.

You have to use “NSKeyedArchiver”.

  1. Schedule your notification
    (don’t use “presentLocalNotificationNow:”, if you use it, this process doesn’t work)

    [[UIApplication sharedApplication] scheduleLocalNotification:notification];

  2. Archive notification with path.

    [NSKeyedArchiver archiveRootObject:notification toFile:path];

  3.  And unarchive the notification with path.

    UILocalNotification *noti = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

  4. Then, call cancelLocalNotification with unarchived notification.

    [[UIApplication sharedApplication] cancelLocalNotification:notification];

  5. Remove archived notification from file system

    [[NSFileManager defaultManager] removeItemAtPath:path error:&error];

From now you know how to remove a single local notification from notification center,
and using this process will help you to handle remote notifications.

    1. Send remote notification as “Silent Notification”.

    2. Download Content from your server and create UILocalNotification.
      (or don’t set any value for “alert” key in ‘aps’ paylod and define other key-value pair for your messages or actions and convert it)

    3. Handle the local notification.


You can check sample project in GitHub.



댓글
댓글쓰기 폼