TruMan1
TruMan1

Reputation: 36158

SwiftUI in a Notification Content Extension?

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

Upvotes: 9

Views: 2124

Answers (2)

Bruno Wernimont
Bruno Wernimont

Reputation: 111

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

Upvotes: 4

jnpdx
jnpdx

Reputation: 52625

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) {
        //
    }
}

Upvotes: 7

Related Questions