3

Can a SwiftUI view be used in a Notification Content Extension? The Xcode template only offers a view controller, could this be done?

TruMan1
  • 30,176
  • 50
  • 162
  • 301

2 Answers2

3

Yes, you should be able to embed a SwiftUI view in the UIViewController using UIHostingController. There are more extensive answers here (Include SwiftUI views in existing UIKit application), but here's a short version using the Xcode template for UNNotificationContentExtension as a base:

class NotificationViewController: UIViewController, UNNotificationContentExtension {
    @IBOutlet var container: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let childView = UIHostingController(rootView: SwiftUIView())
        addChild(childView)
        childView.view.frame = container.bounds
        container.addSubview(childView.view)
        childView.didMove(toParent: self)
    }
    
    func didReceive(_ notification: UNNotification) {
        //
    }
}
jnpdx
  • 35,475
  • 5
  • 43
  • 61
1

Here's how I do it using AutoLayout rules.

...
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
}

http://brunowernimont.me/howtos/2021-06-21-embed-swiftui-view-in-notification-content-extension

https://github.com/brunow/SwiftUILocalNotification