Local Notifications-1

Local Notifications in Swift 3.0

“We all need assistants in today’s life who can remind us our daily tasks and It will be a cherry on the cake if our smart phones play that role!!”

iOS  is packed with this feature with the name of ‘Local Notifications’. They work like reminders and pops on the navigation bar. Simply, with iOS 4 release, notifications which can be scheduled & fired by the system are referred as Local Notifications. Lets dig dipper.

The Requirement:

Now, if I want to enable this feature to my application, what do I do? What I know is –

  1.  The content to display.
  2.  The date to get that reminder on.
  3.  The intervals I want to repeat on
  4.  The actions I want for my user etc..

But,  who to tell all of above and notify according to my requirement. Thus, frameworks come to rescue. You just need to tell your requirements to them & they take the entire load from scheduling to firing, from content to actions etc. UIKit framework (deprecated in iOS 10) & UserNotifications framework (from iOS 10 &Later) provides its classes & methods to handle all of it.

We will deal with both frameworks i.e UIKit (For iOS 9 & Below) & UserNotifications (For iOS 10 & Later)

Note : It is recommendation – UILocalNotification is deprecated in iOS 10. Use UNNotificationRequest instead .

Step 1: The Request

First things first. We need to request the user to allow our application to send him notifications. This will be done at launch of application. Add the following code in

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool method of AppDelegate.swift file

For iOS 9 & below –

 

For iOS 10 &Later-

import UserNotifications framework first – import UserNotifications.

Step 2: The Content:

Now we need to put the details of notification like when to fire it, what title & description of notification will be, What sound it will buzz etc. Then, encapsulating the data into parameters with that content, we will schedule the notification. The notification will be fired after 2 minutes & will be repeated every hour.

For iOS 9 & below –

 

For iOS 10 & Later-

There is a new candy in the bucket list of UserNotifications framework which is attachment. Yes, now you can attach any image, audio, video etc. Also, to set the fire date in UserNotifications framework, we need to make variable of UNCalendarNotificationTrigger & set repeats property there itself.

Step 3: The Actions:

At this point, we are in a position to get the notification but lets give more power to the user and enable some actions with notification. So, lets add actions to our notifications. As, the implementation has drastic differences between iOS 9 & iOS 10, So will deal differently.

Notification Actions in iOS 9 & below:

An action is an object of the UIMutableUserNotificationAction class. This class was introduced in iOS 8, and provides various useful properties so an action can be properly configured like identifier, title, destructive, authenticationRequired, activationMode. For every action, we will set the values to all the aforementioned properties. The first one:

The second one:

As the identifier and title of action suggests, first action “Remind Me Later” will normally just remove notification from Notification Bar. The second action “Set New Reminder” will set new reminder after 10 minutes to give an extra reminder & will bring our application foreground.

When the actions of a notification have been defined, they can then be grouped together in categories.

A category is an object of the UIMutableUserNotificationCategory class, which was also introduced in iOS 8. This class has just one property and one method. The property is a string identifier that uniquely identifies a category (similarly to actions), and the method is used to group the actions together. Next, let’s create a new category for which we will set an identifier. 

Change the UIUserNotificationSettings(types: ,categories:)  and add the category defined above inUIUserNotificationSettings as a parameter.

Last thing left ,  that is to assign category to the object of UILocalNotification along with fireDate, alertTitle, alertBody & repeatInterval set above in code.

Good to go!! Now you have told the framework to add actions to your notification when fired. But, the question arises even if the actions are added how will your application know that a certain action has been performed? Also, because we tell the framework to schedule everything therefore there is nothing in our hand.

This implies that the framework must provide some callback methods to us where we can guide the application to proceed with our code.

So, we will implement delegate method in AppDelegate.swift file which will get the callback on action performed on UIMutableUserNotificationAction actions 

func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, for notification: UILocalNotification, completionHandler: @escaping () -> Void):

Based on the identifiers of actions, both cases we post a notification (NSNotification), specifying a unique identifier. Depending on the identifier value, we will post a notification (NSNotification) for each one, and then in the ViewController class we’ll observe for those notifications. Notice that we have called completionHandler() at the end of this method as this is important for system to tell that we have handled the received actions.

Next, we will add observer in viewController.swift for notifications we set before and then handle actions in our custom methods.

The following custom methods will be added to our viewController file:

So, this finish the action handling with Notification in iOS 9 & below. Next, one case is still left which is that if application is in foreground & notification is fired, then what? Therefore, while application is in foreground, we get a delegate method where we get a call in 

func application(_ application: UIApplication, didReceive notification: UILocalNotification. Add this method in AppDelegate.swift file.

Here we have added an alert which will pop up on screen showing notification message while you are still running application.

This completes the complete Notification Handling in iOS 9 & below.

Notification Actions in iOS10 & later:

We implemented all delegate methods for iOS 9 in AppDelegate file because notification framework for iOS 9 & below comes in UIKit framework(available by default). But this is not the case for iOS 10 & Later as the framework handling notifications needs manual import. So, to implement delegate methods for iOS 10, we need to first confirm UNUserNotificationCenterDelegate to the AppDelegate.swift file.

So, lets make extension of AppDelegate and confirm the protocol  UNUserNotificationCenterDelegate.

Assign its delegate to self in AppDelegate:

Now, the upcoming parts are pretty much similar to the implementation done for iOS 9 in fact simpler than UILocalNotifications. First let us switch & add actions to our notification. We will add the following code in AppDelegate.swift to add actions to our notification:

Next we will add above actions to a category and then register category to  UNUserNotificationCenter

Now tell the content of UNMutableNotificationContent about the category you have defined.

Now, we are just left with handling actions on getting call in our application. So the protocol  (UNUserNotificationCenterDelegate) we confirmed, has 2 methods to handle notifications. The first method –

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) 

gives a callback in the application when any of the defined action is performed & application is in background. Add this method in the extension of AppDelegate :

Based on the action identifier, same tasks will be executed as in iOS 9.

Next, just 1 step ahead which is to add alert when application is in foreground & notification is fired. Implement this method in AppDelegate extension:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) and add alert in it.

The Summary:

Well, this completes the entire implementation on Local Notifications. Keep cool Keep coding!!!

Leave a Reply