I want to use Swift UI to build iOS's Today Extensions, but I don't know how to get started.
Asked
Active
Viewed 3,328 times
4 Answers
5
Check this UIHostingController
tutorial out, easy, straightforward and works like a charm: https://medium.com/@code_cookies/swiftui-embed-swiftui-view-into-the-storyboard-a6fc96e7a0a1

juliancadi
- 987
- 1
- 8
- 23
3
Create SwiftUI view and integrate it with UIHostingController.
You can do this just like use SwiftUI from UIKit.
Create Today Extension (Widget) with SwiftUI
//
// WidgetView.swift
//
import SwiftUI
struct WidgetView: View {
var body: some View {
HStack {
Image(systemName: "globe")
Text("Hello, SwiftUI!")
}
.font(.title)
}
}
//
// TodayViewController.swift
//
import UIKit
import NotificationCenter
import SwiftUI
class TodayViewController: UIViewController, NCWidgetProviding {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let vc = UIHostingController(rootView: WidgetView())
self.addChild(vc)
self.view.addSubview(vc.view)
vc.didMove(toParent: self)
vc.view.translatesAutoresizingMaskIntoConstraints = false
vc.view.heightAnchor.constraint(equalTo: self.view.heightAnchor).isActive = true
vc.view.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
vc.view.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
vc.view.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
vc.view.backgroundColor = UIColor.clear
}
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
completionHandler(NCUpdateResult.newData)
}
}

SoNice
- 121
- 1
- 3
1
Using an instance of UIHostingController as your NSExtensionPrincipalClass to instantiate your SwiftUI view should work on iOS 13.

Kristof Van Landschoot
- 1,427
- 1
- 12
- 30
-
Thank you. I will try it later. – Lxxyx Oct 21 '19 at 17:01
-
How is it working out? Feel free to accept the answer if it helped or ask further questions if it did not... – Kristof Van Landschoot Oct 27 '19 at 20:25
-
I tried to do it your way, but I didn't succeed. May I know where there are documents or Demo for reference? – Lxxyx Oct 31 '19 at 07:13
-
It's easy to show SwiftUI as Today widget using UIHostingController, but it's hard to sync data between Host App with widget using @ binding and @ ObservedObject. – foolbear Apr 06 '20 at 09:43
1
You can now use the new WidgetKit from iOS 14 to build your Widgets using SwiftUI: https://developer.apple.com/documentation/widgetkit/creating-a-widget-extension

J0ker98
- 447
- 5
- 18