Currently, this is how I handle deep link from home widgets.
extension UIWindow {
//
// https://stackoverflow.com/a/58031897/72437
//
static var key: UIWindow? {
// Get connected scenes
UIApplication
.shared
.connectedScenes
.compactMap { $0 as? UIWindowScene }
.flatMap { $0.windows }
.first { $0.isKeyWindow }
}
}
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
// App launched for the first time
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// https://stackoverflow.com/questions/63697132/detect-app-launch-from-widgetkit-widget-extension
if let url = connectionOptions.urlContexts.first?.url {
handleIncomingURL(url)
}
}
// App restored from background stack
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
if let url = URLContexts.first?.url {
handleIncomingURL(url)
}
}
private func handleIncomingURL(_ url: URL) {
guard let rootViewController = UIWindow.key?.rootViewController else { return }
...
}
}
There are 2 cases I need to handle when user clicks on the home widget.
- App launched freshly.
- App restored from background stack.
In my deep link handling logic (function handleIncomingURL
), I need a non nil UIViewController
, so that I can perform appropriate action to handle home widget's deep link.
In case "App restored from background stack", everything is fine because the UIWindow.key?.rootViewController
is able provide me a non nil UIViewController
.
However, in the case of "App launched freshly", I am always getting a nil result from UIWindow.key?.rootViewController
.
Is there a way for me to obtain a non nil UIViewController
during app fresh launched, during home widget's deep link handling?