UserNotifications in Swift 3 (Part 1)

Erica Millado
Yay It’s Erica
Published in
5 min readApr 26, 2017

In iOS development, Apple provides a framework called UserNotifications. This framework assists with the delivery and handling of local and remote notifications. Examples of these types of notifications include notifying users of when to leave for an appointment (I get these an hour before I tutor a student) or if an important news article has been posted (I also get these from the NYTimes).

A local notification is a notification in which the app creates the notification details locally and passes it to device. A remote notification is a notification that uses a server to push data to a user device by using the Apple Push Notification Service.

One thing to note is when it is best to use a local vs. remote notifications. I like to think of using local notifications as “alerts for things that are happening in the background” while remote notifications are “alerts for things that happening immediately and involve a client/server relationship.” Here are some examples:

In this blog, I will walk through the steps needed to create a local notification in a new project.

Step 1: In your AppDelegate.swift file, import the UserNotifications framework at the top.

Step 2: In the applicationDidFinishLaunchingWithOptions( ) method, specify which things you want to request authorizations for by calling UNUserNotificationCenter.current( ).requestAuthorization(:). In the options parameter, specify what options you want to include (alert? sound? badge?) A badge looks like this red circle in the top right corner of the icon:

Step 3: Handle the completion error how you see fit. For now, I am just going to print the error if there is one.

Step 4: In the ViewController.swift file, import the UserNotifications framework.

Step 5: In your storyboard, place a button and a label on the viewController. Make sure to constrain both of these using AutoLayout. Use Assistant Editor to create an IBOutlet for the label.

Step 6: Create an IBAction for the button. When tapped, this button will generate a notification that will display a math problem (math rocks!)

Step 7: Generate the content, or the actual text of the notification you want the user to see. You can specify the title, subtitle, body, badge number, and category identifier. Here, you’ll see that I am going to give the user a math quiz question that asks them “What is the equation for slope-intercept form?”

Step 8: Create a trigger, which specifies what conditions will force this notification to fire. This quizTrigger of UNTimeIntervalNotificationTrigger type is an example but there are other types that we can look into in future blogs. Here I give a trigger a time delay of 2 seconds that will not repeat.

Step 9: Create a request that asks the user if it’s okay to send them local notifications. Make sure this request has a string identifier like mine “mathQuiz.”

Step 10: Schedule our notification by calling UNUserNotificationCenter.current( ).add(:) with our request.

Step 11: Handle the completion error. For now, I am just printing the error.

Step 12 & 13: Adopt the UNUserNotificationCenterDelegate protocol and set the ViewController as its delegate.

Step 14: Implement the required UNUserNotificationCenterDelegate method userNotificationCenterWillPresentNotification(:). This method presents the notification in the app. Meaning, while the app is currently open on the device screen, the notification will appear at the top.

Step 15: Call the completionHandler with specifics on how you want to handle the notification. Here, I call the completionHandler with an .alert and a .sound.

Step 16: Implement the required UNUserNotificationCenterDelegate method userNotificationCenterDidReceiveResponse(:).

Step 17: Here, handle the actions you want to associate with your notification. These response.actionIdentifiers will be the different answer choices that a user can choose from for my mathQuiz. I make sure to change the label’s text appropriately given their chosen answer.

Back in the AppDelegate.swift file,

Step 18: For our notification, since we are displaying a mathQuiz question, we need to create actions for each of our answer choices. These actions are collectively part of a category, which indicates the purpose with which we are using the actions. Here, I create four actions to represent four different multiple choice options to my math question. You’ll note that chose to have these actions displayed in the .foreground, which means that when the user taps the action, it will open up the app to present to the user.

Step 19: Here, we create a category that will encompass our choice actions. Note that my identifier “mathQuizCategory” is the same one I sent with my content in my ViewController.swift file.

Step 20: I call the UNUserNotificationCenter.current().setNotificationCategories( ) with my mathQuizCategory. This sets the categories and its actions for the notification I created.

Voila! You now have got a local notification working with actions!

Note: I made a typo in my choiceD formula. It should be “D = rt”.

You can see my source code here.

Let me know how you used a local notification in your app!

Resources:

Local and Remote Notifications Overview — Apple Documentation

--

--