Creating local notifications

Local notifications are created and stored locally on the device. They are very similar to push notifications in terms of the content they can contain. The way that content is created is quite different though. For instance, you can't create a local notification for content that doesn't exist yet.

In the context of a news app, this means that a server could push a news item to the application when needed. If you create the notification locally, you don't know what tomorrow's big news item will be, so you can't schedule a notification with content for this news item yet. This is an important distinction between local and push notifications that you should keep in mind when choosing whether you should create a notification locally, or if you should leave it up to a server to create the notification.

The following code snippet demonstrates the creation of a notification for a reminder. You should add this snippet to the NotificationsHelper:

func createNotificationContentForReminder(_ reminder: Reminder) -> UNMutableNotificationContent {
  let content = UNMutableNotificationContent()

  content.title = "Reminder"
  content.body = reminder.title ?? ""
  content.badge = 1

  content.userInfo = ["reminder-uuid": reminder.identifier?.uuidString]

  return content
}

This preceding code contains data that is quite similar to the JSON you saw previously. The main difference is that you create an instance of UNMutableNotificationContent and assign values to it, instead of defining the entire notification using JSON. A lot of the options that are available in the push example are also available for local notifications. You can add custom properties, such as the unique identifier for a reminder, to a UNNotification object's userInfo dictionary. You can also assign a custom sound, attachment, and more to local notifications, just as you can for push notifications.

Now that you know how to create notification contents, let's see how you can schedule them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.79.60