Notification with Actions

Overview

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

  • Done task action
  • Remind me later action
  • 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

Set actions for the default context

taskCategory.setActions([doneAction, remindLaterAction, addNewTaskAction],
forContext: UIUserNotificationActionContext.Default)

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.

//Notification Registration *****************************************

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

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]

UIApplication.sharedApplication().scheduleLocalNotification(notification)

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)
}
completionHandler()
}

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

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

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

I have posted different notification in notification center for different activities and passed Task class object to perform any action on a 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
break
}
}
// Remove particular item from Array
for (index, element) in enumerate(arrTaskLists) {
if element == task.title {
arrTaskLists.removeAtIndex(index)
}
}
tblTasks.reloadData()

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

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
break
}
}

// 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]

UIApplication.sharedApplication().scheduleLocalNotification(notification)
}

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) {
self.txtTask.becomeFirstResponder()
}

Summary

All you have to done for interactive notification is

  • Define notification actions
  • Define category for both minimal and default context
  • Register notification.
  • Schedule notification for particular date and time.
  • handle notification action as per user’s selected action.
  • F

  • A

  • Q

Notification Actions allow users to interact directly with an application from a notification without opening the application completely. They can perform predefined tasks such as marking an item as done, postponing a reminder, or starting a new task. This feature was introduced in iOS 8 to make notifications more useful and interactive.

The demo application is designed to let users create tasks and schedule reminders for those tasks. When a reminder notification appears, users can directly choose actions such as Done, Remind Me Later, or Add New Task. This allows common task-related operations to be performed directly from the notification.

`UIMutableUserNotificationAction` is used to define an action that a user can perform from a notification. It provides properties such as identifier, title, destructive, authenticationRequired, and activationMode to control how the action behaves. Developers can use these properties to clearly define what happens when a user selects a particular notification action.

A notification action includes several properties that control its behavior and appearance. The identifier uniquely identifies the action, while the title defines the text displayed to the user; destructive determines whether the action is treated as a potentially destructive operation, and authenticationRequired can require the user to unlock the device. The activationMode determines whether the application performs the action in the background or opens in the foreground.

The demo defines three actions: Done Task, Remind Me Later, and Add New Task. The Done Task action allows the user to complete a task, while Remind Me Later schedules another reminder for the task. The Add New Task action opens the application so that the user can immediately start entering a new task.

The Default context is used when the notification is displayed as an alert while the device is unlocked, allowing the actions grouped under this context to be shown to the user. The Minimal context is used for situations such as notification banners or when the device is locked, where fewer actions can be displayed. In the example, the Default context contains all three actions, while the Minimal context contains only Done and Remind Me Later.

Notification actions are grouped together using the `UIMutableUserNotificationCategory` class. A category is given a unique identifier and the required actions are assigned to it using the `setActions()` method for the appropriate notification context. This category is then included when notification settings are registered so the system knows which actions should be available for the notification.

A local notification is created using `UILocalNotification` and configured with information such as the alert message, sound, fire date, category, and task details. The task deadline is assigned to the notification's `fireDate`, which determines when the reminder should appear. The notification can then be scheduled using `scheduleLocalNotification()` so the user receives the reminder even when the application is not running.

The application stores task information such as the task title and a unique identifier in the notification's `userInfo` property. When the notification action is triggered, the application retrieves the task deadline from `fireDate` and other task information from `userInfo`. The unique identifier makes it possible to find and modify the exact task associated with the notification.

When a user selects an action, the `handleActionWithIdentifier` method in the application's AppDelegate is called. The method checks the action identifier to determine whether the user selected Done Task, Remind Later, or Add New Task and then performs the corresponding operation. The example posts separate notifications through `NSNotificationCenter` so the appropriate part of the application can handle each action.

When the Done Task action is selected, the application identifies the related task using its unique identifier and cancels its scheduled local notification. It then removes the completed task from the task list and reloads the table view so the updated list is displayed. The updated task list is also stored using `NSUserDefaults` so the change can be retained.

When the Remind Me Later action is selected, the application first finds and cancels the existing notification associated with that task. It then creates a new local notification and schedules it for five minutes later while keeping the task information attached to it. This allows the user to postpone the reminder without losing the original task.

The Add New Task action is configured with a foreground activation mode, so selecting it launches or brings the application to the foreground. Once the application is active, the `addNewTask` method is called to focus the task text field. The `becomeFirstResponder()` method is then used to place the cursor in the text field so the user can immediately enter a new task.

Observers are added so the appropriate part of the application can respond when a notification action has been selected. The AppDelegate posts different notifications for actions such as completing a task, postponing a reminder, or adding a new task. The view controller observes these notifications and calls the corresponding methods to update the task list or user interface.

Want to Scale Your Business? Let’s Meet & Discuss!

Canada Flag

CANADA

30 Eglinton Ave W Mississauga, Ontario L5R 3E7

India Flag

INDIA

3rd floor Purusharth Plaza, Amin Marg, Rajkot, Gujarat. 360002

India Flag

INDIA

1116, Zion Z1, Sindhu Bhavan Marg, Nr. Maple County Road, Bodakdev, Ahmedabad, Gujarat. 380059

Get a Quote Now

Let's delve into a thorough understanding of your challenges and explore potential solutions together