Notification Content Extension is an extension to your app which provides a custom interface to your notification in the notification center.
Content extensions provide a great user experience because they’re integrated with the notification center and it runs in a process independent of the main process. However, it is mandatory for the main application to receive feedback when displaying the content extension. In this blog, we will discuss how to create a content extension.
Create a Content Extension:
Add a Notification Content Extension
target to your application by selecting File -> New -> Target, and then selecting the Notification Content Extension
icon in the Application Extension
section as follow:
The extension that is created contains a NotificationViewController
that adheres to the UNNotificationContentExtension
.
If a UIViewController inside a Notification Content Extension adheres to the UNNotificationContentExtension, we are able to access the notification content and we can customize its UI. In the extension, there’s a MainInterface.storyboard that contains a single controller associated with the NotificationViewController previously mentioned. We can use this storyboard to customize the notification UI using an interface builder.
We can change the UI with the notification contents we receive in func didReceive(_ notification: UNNotification)
.Your code will look like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import UIKit import UserNotifications import UserNotificationsUI class NotificationViewController: UIViewController, UNNotificationContentExtension { @IBOutlet weak var image: UIImageView! @IBOutlet weak var name: UILabel! @IBOutlet var desc: UILabel! func didReceive(_ notification: UNNotification) { if let validName = notification.request.content.userInfo["title"] as? String, let validDesc = notification.request.content.userInfo["description"] as? String, let validImage = notification.request.content.userInfo["imageName"] as? String{ name.text = validName desc.text = validDesc image.image = UIImage(named: validImage) } } } |
Now we have to go back to our notification content extension and set some attributes in its info.plist. In particular, we have to set:
UNNotificationExtensionCategory
, the notification category that we want to customize.UNNotificationExtensionDefaultContentHidden
to hide the standard notification content when the user long presses the notification.- if needed it is possible also to set the UNNotificationExtensionInitialContentSizeRatio to a value different than 1 to customize the aspect ratio of our notification.
We’re ready to test our implementation.
Conclusion:
That’s all for Notification Content App Extension on iOS. Let’s start to test them in your app. To read more of my blogs, please visit this link. Thank you for reading this blog.