Swift 3.0 — UserNotifications

Notifications are objects can carry information, a user info dictionary and be broadcast to multiple receivers. The new UserNotifications framework (launched by Apple with iOS 10) supports the delivery and handeling the local and remote notifications.

Notification types:

  1. A local notification is an object, that you can schedule to be delivered to your app at the specific time, even if your app is in the background or not running. With local notification you are waking up your app. Local notifications are visible to the user and the user can take an action on them. At the same time user doesn’t have to be involve in the taking action. Notification can be send inside your app to the specific contest of your app.
  2. Push notification (also known as remote notifications) is sent via server. Apple Push Notification service(APNs) transports and routes remote notifications to your apps to your provider to each user’s device. Provider sends the notification and the device token to the APSs, that pushes notification to the user device and the operational system handles the delivery of the notification to the app.

User can get notified:

  1. An on screen alert or banner
  2. A badge on the app’s icon
  3. A sound that accompanies alert, banner, or badge

SDK ‘iOS 10.0’(Xcode 8) introduces the UserNotification.framework. It’s independent from UIKit, which supports the delivery and handling local and remote notifications based on the specific conditions, such as location, time interval, calendar, or location.

UserNotificationsUI.framework lets you customized the apperance of the local and remote notifications when they appear on the local device.

Note: Old API also works fine with SDK ‘iOS 10.0’(Xcode 8).

You have to import UserNotifications framework in every file where you need notifications.

AppDelegate.swift

Registration of notification for local and remote notifications. Notifications become independant from UIKit.

AppDelegate.swift (inside of the function didFinishLaunchingWithOptions:)
Result of registration.

A UNNotificationRequest object is used to schedule a local notification and manages the content for a delivered notification. A notification request object contains: UNNotificationContent object with the contents of the notification and UNNotificationTrigger object that specifies the conditions that trigger the delivery of the notification.

There are three types of trigger:

  1. Time interval — can set how often do you want to run notification, or how big delay do you want to set.
  2. Calendar — can set exact time for trigging.
  3. Location — schedule notification delivery when you enter or leave certain location.

Let’s create local notification:

ViewController.swift. Example of the local notification.
AppDelegate.swift. Example of the local notifications.
Result
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.