Topics

#261: Rich Notifications 💰💭

Topics

Today we'll continue our look at Notifications in iOS 10 by looking at the new "rich" attributes we can use to give our notifications titles, subtitles, and even media! Let's check it out.

Most of this code will center around our old friend UNNotificationContent:

let notification = UNMutableNotificationContent()

notification.categoryIdentifier = "asteroid-detected"

notification.title = "Asteroid Detected! 🚀"
notification.body = "Collision imminent. Immediate action required!"

We're already using two new fields here: title and body. This allows us to properly highlight the important and extra information in our notification's UI:

Nice.

Now, it'd be really great if we could show the user an image of the giant space rock they're hurdling towards. Let's attach some media to do this:

if let attachment = try? UNNotificationAttachment(
  identifier: "asteroid-id-123-photo",
  url: asteroidImageURL
) {
  notification.attachments.append(attachment)
}

Heads up: That will need to be a local file URL, not a remote one.

Now, when our notification is shown, we see a nice little preview of the asteroid:

One small note here: The thumbnail image shown here is the result of adding padding manually to the image to account for the the system's aggressive cropping.

There is a way to pass a dictionary of options to UNNotificationAttachement. There's even a key called UNNotificationAttachmentOptionsThumbnailClippingRectKey.

This key requires a "normalized" CGRect describing how the image should be clipped.

Setting this key to CGRect(x: 0, y: 0, width: 1, height: 1) should allow the whole thing to be visible, but it seems the system ignores this value entirely as of Beta 6.

OpenRadar #27708976, rdar://27708976