7Oct 2015

Notification with Actions

72 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
1
2
3
4
5
6
7
 // Clear all tasks
let doneAction = UIMutableUserNotificationAction()
doneAction.identifier = “DoneTask”
doneAction.title = "Done"
doneAction.activationMode = UIUserNotificationActivationMode.Background
doneAction.authenticationRequired = true
doneAction.destructive = false
1
2
3
4
5
6
7
// 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
1
2
3
4
5
6
7
// 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.

1
2
3
 // 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.

1
 // 3. 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.

1
2
3
4
5
6
7
 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.

1
2
3
4
5
6
7
8
9
10
11
 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 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.

1
2
3
 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.

1
2
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.

1
2
 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.

1
2
3
 func addNewTask(notification: NSNotification) {
self.txtTask.becomeFirstResponder()
}

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.
Brevity

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.

72 thoughts on “Notification with Actions

  1. 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!

  2. 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

  3. 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!

  4. 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.

  5. 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!

  6. 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.

  7. 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.

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

  10. 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.

  11. Fantastic goods from you, man. I’ve understand your stuff previous to and you’re just too magnificent. I really like what you have acquired here, really like what you’re saying and the way in which you say it. You make it enjoyable and you still take care of to keep it sensible. I cant wait to read far more from you. This is actually a wonderful site.

  12. I’m still learning from you, as I’m improving myself. I absolutely enjoy reading all that is written on your blog.Keep the information coming. I loved it!

  13. You really make it seem so easy with your presentation but I find this matter to be really something that I think I would never understand. It seems too complex and very broad for me. I am looking forward for your next post, I’ll try to get the hang of it!

  14. Hello, Neat post. There is a problem along with your site in internet explorer, may test this still is the marketplace leader and a good component of other people will miss your fantastic writing because of this problem.

  15. Someone necessarily lend a hand to make seriously articles I would state. This is the first time I frequented your website page and up to now? I amazed with the research you made to create this actual put up extraordinary. Wonderful activity!

  16. It is actually a great and helpful piece of info. I am satisfied that you simply shared this helpful info with us. Please stay us informed like this. Thanks for sharing.

  17. An fascinating discussion is price comment. I feel that you need to write extra on this topic, it might not be a taboo subject but typically individuals are not sufficient to speak on such topics. To the next. Cheers

  18. I think other website proprietors should take this site as an model, very clean and great user friendly style and design, as well as the content. You’re an expert in this topic!

  19. Great blog here! Also your site so much up very fast! What web host are you using? Can I get your affiliate link to your host? I desire my site loaded up as fast as yours lol

  20. Spot on with this write-up, I really think this web site wants rather more consideration. It will probably be once more to learn rather more, thanks for that info.

  21. I was just looking for this info for some time. After six hours of continuous Googleing, finally I got it in your website. I wonder what is the lack of Google strategy that do not rank this type of informative web sites in top of the list. Generally the top sites are full of garbage.

  22. whoah this blog is wonderful i love studying your posts. Keep up the great work! You already know, a lot of individuals are looking around for this info, you could aid them greatly.

  23. I would like to thnkx for the efforts you’ve put in writing this website. I’m hoping the same high-grade blog post from you in the upcoming also. In fact your creative writing skills has inspired me to get my own website now. Really the blogging is spreading its wings fast. Your write up is a great example of it.

  24. I’ve been browsing online more than 3 hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. In my opinion, if all site owners and bloggers made good content as you did, the web will be much more useful than ever before.

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>