Can a SwiftUI view be used in a Notification Content Extension? The Xcode template only offers a view controller, could this be done?
Asked
Active
Viewed 469 times
2 Answers
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
-
Has this changed at WWDC 2021? – TruMan1 Jun 13 '21 at 22:54
-
Not that I'm aware of – jnpdx Jun 13 '21 at 22:56
-
There's `UNNotificationContentProviding` but there's no documentation about it, I wonder if this could be it: https://developer.apple.com/documentation/usernotifications/unnotificationcontentproviding – TruMan1 Jun 13 '21 at 22:59
-
That doesn't look related to SwiftUI at all. – jnpdx Jun 13 '21 at 23:01
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
Bruno Wernimont
- 81
- 1
- 4