Topics

#260: New Notifications Capabilities 💭

Topics

Today we'll continue our look at Notifications in iOS 10 by checking out some new capabilities for interacting with the user's notification preferences, and also the notifications we've requested and setup with the notification center. Let's begin.

First up, we finally have a way to "ask" the system for the user's current notification preferences state:

UNUserNotificationCenter.current()
  .getNotificationSettings { settings in 
    // settings is a beautifully descriptive
    // UNNotificationSettings object.
  }

Inside this fancy UNNotificationSettings object is a wealth of detail about exactly how the user has configured our app's notifications to work. Everything from authorizationStatus to alertStyle. Neat!

Next up, since we've been requesting all these notifications to be triggered, we can now ask the system to give us the list of pending notifications. (Notifications that are scheduled, but haven't been displayed yet).

UNUserNotificationCenter.current()
  .getPendingNotificationRequests { requests in
    // requests is an array
    // of UNNotificationRequest objects.
  }

From here, we can take the identifier of any of these requests, and use it to (for example) "unschedule" it:

UNUserNotificationCenter.current()
  .removePendingNotificationRequests(
    withIdentifiers: ["asteroid-id-123"]
  )

Functions also exist to remove all pending notifications at once.

Last but certainly not least, we can actually do this exact same type of management on notifications that have already been shown to the user.

That's right we can retrieve the notifications that are currently in Notification Center like this:

UNUserNotificationCenter.current()
  .getDeliveredNotifications { (notifications) in
    _ = notifications.map { print($0.request.identifier) }
  }

We can also remove any or all of these notifications by identifier as well. Super neat!