@brunowernimont
Let's connect together

SwiftUI view in Notification Content Extension

June 21, 2021

SwiftUI Notifications

A long time ago Apple introduced Notification Content Extension, these notifications are custom views in a storyboard, but we’re in 2021 and we all love SwiftUI right?

Thum
Thum showing a list of nearby to-do in SwiftUI.

Create SwiftUI view

Let’s start by creating a simple SwiftUI view that we’ll embed into your notification content.

struct NotificationView: View {
    var body: some View {
        Text("Hello, World this is a SwiftUI view!")
            .fontWeight(.bold)
    }
}

Embed the view into the NotificationViewController

Now that we have created the view, we need to embed it into a UIHostingController and add constraints.

...
var hostingView: UIHostingController<NotificationView>!
...

func didReceive(_ notification: UNNotification) {
  let notificationView = NotificationView()
  hostingView = UIHostingController(rootView: notificationView)
  
  self.view.addSubview(hostingView.view)
  hostingView.view.translatesAutoresizingMaskIntoConstraints = false
  
  hostingView.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
  hostingView.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
  hostingView.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
  hostingView.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
}

Don’t forget to remove unused views in the generated storyboard.

Sample project.