Get A Quote
7Oct 2015

Notification with Actions

41 Comments   IPhone
Notification with Action in iPhone

Notifications are the way to get user’s attention or communicate with user even application is not running. Notifications are used to notify user about some event or actions, or just remind user for some important task.

From iOS 8 Apple introduce interesting improvement in Notification that is Notification Action. With this, user can directly interact with the application without even opening the application.

Let’s create a demo application that allow you to add tasks and schedule reminder for that particular task. Add notification action for done task, remind me later and to add new task in the task list.

Note : To make it simple this example only works with Local Notification, you also can add Notification Action to push notification.

Step : 1 Create a new project in xCode name it “Notifications Demo”.

Step : 2 Register notification with Actions

Create a method name it registerNotification().

Now define notification actions, before it understand the notification actions, class used to define it and its property.

Notification Actions :

Notification Actions defines the actions performed by user when notification arrives.

Define Notification Actions using UIMutableUserNotificationAction class.

This class provides various properties to configure actions.

Identifier : It is a string value that uniquely identifies the action among all other action in the application. It is useful to identify the action when user chose particular action when notification fire.

title : It is a string value that defines action title. Set appropriate title so, that user can easily identify the action performed by selecting it.

destructive : It is a bool value. When it set to true the action button display with red background. Generally it is used for deletion or any other critical actions.

authenticationRequired : It is a bool value. When it is true user have to authenticate himself to device before perform any action, that means user have to insert the unlock code to perform the action.

activationMode : It is an enum property. It defines whether the app should run in background or in foreground when the action performed.

In this demo application we are defining 3 notification actions in registerNotification() method, that is..

  1. Done task action
  2. Remind me later action
  3. Add new task action
 // Clear all tasks
let doneAction = UIMutableUserNotificationAction()
doneAction.identifier = “DoneTask”
doneAction.title = "Done"
doneAction.activationMode = UIUserNotificationActivationMode.Background
doneAction.authenticationRequired = true
doneAction.destructive = false
// done particular task
let remindLaterAction = UIMutableUserNotificationAction()
remindLaterAction.identifier = “RemindLater”
remindLaterAction.title = "Remind in 5 mins"
remindLaterAction.activationMode = UIUserNotificationActivationMode.Background
remindLaterAction.authenticationRequired = true
remindLaterAction.destructive = true
// Add new Task
let addNewTaskAction = UIMutableUserNotificationAction()
addNewTaskAction.identifier =”AddNewTask”
addNewTaskAction.title = "Add New Task"
addNewTaskAction.activationMode = UIUserNotificationActivationMode.Foreground
addNewTaskAction.authenticationRequired = false
addNewTaskAction.destructive = false

Remind later and Done task action will be performed in background, but add new task action require to run the app in foreground so its activation mode is set to foreground.

Now after defining actions you have to group them together in a category. You have to define category if you want to add notification action in your notification. Define category using UIMutableUserNotificationCategory class and set category identifier using its identifier property. It has a method setActions(), It used to group actions together.

 // Category
let taskCategory = UIMutableUserNotificationCategory()
taskCategory.identifier = categoryId

// A. Set actions for the default context
taskCategory.setActions([doneAction, remindLaterAction, addNewTaskAction],
forContext: UIUserNotificationActionContext.Default)

// B. Set actions for the minimal context
taskCategory.setActions([doneAction, remindLaterAction],
forContext: UIUserNotificationActionContext.Minimal)

Here, I have defined actions for default context and minimal context. Let understand what is default context and minimal context.

Default context : Default context refers to the alert, when your application accepts to display notification for your application as alert then all the actions grouped inside default context displayed as alert when notification fired (When device is unlocked). Minimal context : Minimal context refers to the notification banner, when your application accepts to display notification for your application as banner or your device is locked then actions grouped inside minimal context is displayed. It does not show more than 2 actions. 

Now define the type and other settings of notification and register it.

 // 3. Notification Registration *****************************************

let types = UIUserNotificationType.Alert | UIUserNotificationType.Sound
let settings = UIUserNotificationSettings(forTypes: types, categories: NSSet(object: taskCategory) as Set)

Call this registerNotification() method from applicationDidFinishLaunching method in your AppDelegate.

Step : 3 Create UI add new task and List all task In your main.storyboard file add a textfield and a button that allows to add new task. When user tap add button ask to select date and time from date picker to schedule reminder for that task. Also list all added task below in a table view. Now after user add new task with reminder date and time schedule notification as below in your viewController class.

 let notification = UILocalNotification()
notification.alertBody = "Hey, Have you completed your task?"
notification.soundName = UILocalNotificationDefaultSoundName
notification.fireDate = task.deadline // Date and time selected from DatePicker
notification.category = categoryId
// category id which you define at the time of defining category for notification actions.
notification.userInfo = ["title": task.title, "UUID": task.UUID]


Here i have passed task.deadline in fireDate property.
task is object of model class Task, which have 3 properties that is deadline, title and UUID.

so that it’s easy to identify for which task the notification is fired.

Step : 4 Handle notification Action

When notification fired handleActionWithIdentifier method will be called. You have to add that method inside your AppDelegate file.

 func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {
var task = Task(deadline: notification.fireDate!, title: notification.userInfo!["title"] as! String, UUID: notification.userInfo!["UUID"] as! String!)
if identifier == “DoneTask” {
NSNotificationCenter.defaultCenter().postNotificationName("DoneTaskNotification", object: task)
} else if identifier == “RemindLater” {
NSNotificationCenter.defaultCenter().postNotificationName("RemindLaterNotification", object: task)
} else {
NSNotificationCenter.defaultCenter().postNotificationName("AddNewTaskNotification", object: nil)

In this method I initialized Task class object with its property deadline, title and UUID.

you can get deadline from firedate property of the notification, title and UUID can be get from userInfo that is previously set at time of scheduling the notification.

Now check which action is performed. You can check it using identifier which you have set at time of defining notification actions and perform particular task.

I have post different notification in notification center for different action and passed Task class object to perform any action on particular task.

Step : 5 Add Observer for your notification center to handler notification action

Now you have added handleActionWithIdentifier method in your AppDelegate, it will post particular notification in notification center when any action performed. So, you have to add observer for that notifications.
Add Observer for notification center in your viewDidLoad() method.

 NSNotificationCenter.defaultCenter().addObserver(self, selector: "doneTask:", name: "DoneTaskNotification", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "remindLaterTask:", name: "RemindLaterNotification", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "addNewTask:", name: "AddNewTaskNotification", object: nil)

Add selector for all the notification posted.

Add doneTask: selector for “DoneTaskNotification”

In that selector cancel local notification from that particular task object, remove that task from task list displayed.

func doneTask(notification: NSNotification) {
let task: Task = notification.object as! Task

// Remove notification for particular task
for notification in UIApplication.sharedApplication().scheduledLocalNotifications as! [UILocalNotification] { // loop through notifications…
if (notification.userInfo![“UUID”] as! String == task.UUID) { // …and cancel the notification that corresponds to this TodoItem instance (matched by UUID)
UIApplication.sharedApplication().cancelLocalNotification(notification) // there should be a maximum of one match on UUID
// Remove particular item from Array
for (index, element) in enumerate(arrTaskLists) {
if element == task.title {

// Change array of NSUserDefault
NSUserDefaults.standardUserDefaults().setObject(arrTaskLists, forKey: KEY_TASK_ARRAY)

Add remindLaterTask: selector for “RemindLaterNotification”
In that selector cancel local notification for particular task and schedule notification and set its fireDate after 5 mins.

 func remindLaterTask(notification: NSNotification) {
let task: Task = notification.object as! Task

// Remove notification for particular task
for notification in UIApplication.sharedApplication().scheduledLocalNotifications as! [UILocalNotification] { // loop through notifications…
if (notification.userInfo![“UUID”] as! String == task.UUID) { // …and cancel the notification that corresponds to this TodoItem instance (matched by UUID)
UIApplication.sharedApplication().cancelLocalNotification(notification) // there should be a maximum of one match on UUID

// Schedule notification after 5 mins
let notification = UILocalNotification()
notification.alertBody = “Hey, Have you completed your task?”
notification.soundName = UILocalNotificationDefaultSoundName
notification.fireDate = NSDate().dateByAddingTimeInterval(5 * 60)
notification.category = categoryId
notification.userInfo = [“title”: task.title, “UUID”: task.UUID]


Add addNewTask: selector for “AddNewTaskNotification”
This notification action’s activation mode is set to foreground so when this action fired your application is launched in foreground. So, to allow user to add new task just set your cursor to add task textfield by calling textfield’s becomeFirstResponder() method.

 func addNewTask(notification: NSNotification) {

Summary :

All you have to done for interactive notification is..

  1. Define notification actions
  2. Define category for both minimal and default context
  3. Register notification.
  4. Schedule notification for particular date and time.
  5. handle notification action as per user’s selected action.

About Admin

Brevity Software provides services such as : Web design and development, Mobile application development, Web application development, Travel portal development, Event management systems, Transport & Logistics Software, Enterprise Mobility Solutions, eCommerce & M Commerce application and many more.

41 thoughts on “Notification with Actions

  1. WONDERFUL Post.thanks for share..more wait .. ?

  2. I am typically to blogging and i actually admire your content. The article has actually peaks my interest. I am going to bookmark your website and hold checking for new information.

  3. Keep working ,terrific job!

  4. We are a group of volunteers and starting a new scheme in our community. Your web site provided us with valuable info to work on. You have done an impressive job and our whole community will be grateful to you.

  5. ultra boost says:

    There may be noticeably a bundle to learn about this. I assume you made certain nice factors in features also.

  6. I have to check with you here. Which is not one thing I often do! I get pleasure from studying a post that may make people think. Also, thanks for allowing me to comment!

  7. Website says:

    I just want to tell you that I am new to writing a blog and totally cherished your information. Most likely I am going to store your blog post . You seriously have excellent article blog posts. Get Pleasure From it for giving out with us the best domain post

  8. Hi there, just became alert to your blog through Google, and found that it is truly informative. I’m gonna watch out for brussels. I’ll appreciate if you continue this in future. Numerous people will be benefited from your writing. Cheers!

  9. I think other website proprietors should take this website as an model, very clean and great user friendly style and design, let alone the content. You are an expert in this topic!

  10. Game Design says:

    Well I really enjoyed reading it. This article provided by you is very effective for correct planning.

  11. 4x4 Pickup says:

    Hi there, You’ve done a great job. I will certainly digg it and personally suggest to my friends. I’m confident they’ll be benefited from this website.

  12. This is very interesting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your wonderful post. Also, I’ve shared your site in my social networks!

  13. I am continually searching online for tips that can assist me. Thank you!

  14. Definitely, what a magnificent blog and revealing posts, I surely will bookmark your website.Best Regards!

  15. Great post. I was checking continuously this blog and I’m impressed! Extremely helpful info specially the last part :) I care for such information a lot. I was looking for this particular information for a very long time. Thank you and good luck.

  16. Hello There. I found your blog using msn. This is a really well written article. I’ll be sure to bookmark it and come back to read more of your useful info. Thanks for the post. I’ll definitely comeback.

  17. Hey, you used to write excellent, but the last several posts have been kinda boring¡K I miss your great writings. Past several posts are just a little out of track! come on!

  18. Branding says:

    Useful info. Lucky me I found your site unintentionally, and I am shocked why this twist of fate didn’t happened in advance! I bookmarked it.

  19. Technology says:

    Awsome blog! I am loving it!! Will come back again. I am taking your feeds also

  20. Great website! I am loving it!! Will be back later to read some more. I am taking your feeds also

  21. Real Estate says:

    Excellent read, I just passed this onto a friend who was doing some research on that. And he just bought me lunch since I found it for him smile Thus let me rephrase that: Thanks for lunch!

  22. It is actually a great and useful piece of information. I¡¦m glad that you simply shared this helpful info with us. Please stay us up to date like this. Thanks for sharing.

  23. Wow, amazing blog format! How long have you ever been blogging for? you make blogging look easy. The entire glance of your site is fantastic, as well as the content material!

  24. Business says:

    Thank you for sharing excellent informations. Your web site is very cool. I’m impressed by the details that you have on this website. It reveals how nicely you understand this subject. Bookmarked this web page, will come back for extra articles. You, my pal, ROCK! I found simply the info I already searched everywhere and simply could not come across. What a perfect web site.

  25. Very nice article and straight to the point. I don’t know if this is actually the best place to ask but do you people have any ideea where to get some professional writers? Thanks :)

  26. Business says:

    Very nice article and right to the point.

  27. Automotive says:

    Very good written information. It will be helpful to anybody who employess it, as well as me. Keep up the good work – i will definitely read more posts.

  28. Automotive says:

    Hey, you used to write great, but the last several posts have been kinda boring¡K I miss your great writings. Past few posts are just a bit out of track! come on!

  29. Business says:

    I savor, result in I discovered exactly what I was looking for. You’ve ended my four day lengthy hunt! God Bless you man. Have a great day.

  30. Pet says:

    I really appreciate this post. I¡¦ve been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thank you again

  31. Hi there, I discovered your website by the use of Google at the same time as searching for a similar subject, your website came up, it appears good. I’ve bookmarked it in my google bookmarks.

  32. I was suggested this blog by means of my cousin. I am not certain whether this publish is written via him as nobody ese recognise such certain about my difficulty.
    You are wonderful! Thanks!

  33. HI… Very informative post . Thanks for sharing. I am a mobile app developer So This will be really helpfulll for me in my future career. Good job that you have done. I really appreciate your work.

  34. It’s really a great and helpful piece of information. I am
    glad that you just shared this useful information with us.
    Please stay us informed like this. Thanks for sharing.

  35. Kandi says:

    I see you don’t monetize your website, there is one cool
    method to make extra income, it will work with your website perfectly,

  36. Halley says:

    I enjoy, lead to I found just what I used
    to be having a look for. You have ended my four day long
    hunt! God Bless you man. Have a nice day.

  37. eebest8 seo says:

    I really enjoy the article post. Want more.

  38. UyGDWm It is in reality a great and helpful piece of information. I am glad that you just shared this helpful info with us. Please keep us informed like this. Thank you for sharing.

  39. Great article, exactly what I was looking for.

  40. Hi there Dear, are you in fact visiting this site regularly, if so then you will without doubt get good know-how.

  41. Skwierzyna says:

    Hello! I just want to give a huge thumbs up for the nice data you may have right here on this post. I will probably be coming again to your weblog for extra soon.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>