Reputation: 143
I have created a today extension with some UIButtons and I want to open a specific view controller when the user taps a button. It works right now when the main app is open, but when it is closed then it will only open the main app and dont navigate to my specific view controller.
What I have done: I have set up the URL Sheme and wrote the OpenURL Code if button is pressed in TodayExtension View Controller.
@objc func buttonClick(sender: UIButton) {
let tag = sender.tag
if let url = URL(string: "OpenURL://\(tag)")
{
self.extensionContext?.open(url, completionHandler: nil)
}
}
In SceneDelegate I wrote the code to navigate to specific view controller in func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
if let url = URLContexts.first?.url {
if url.scheme == "OpenURL" {
guard let rootViewController = (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window?.rootViewController else {
return
}
let storyboard = UIStoryboard(name: "Groups", bundle: nil)
if let rootVC = storyboard.instantiateViewController(withIdentifier: "Create") as? CreateSingleGroupViewController,
let tabBarController = rootViewController as? UITabBarController,
let navController = tabBarController.selectedViewController as? UINavigationController {
navController.pushViewController(rootVC, animated: true)
rootVC.buttonTag = Int(url.host!)
}
}
}
}
But like i said this only works when the main app is opened before. What do I have to do that this works even if the main ap is closed?
With the help from Google I figured out that I have to set up the func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
function but I dont know how. What I have wrote is
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let _ = (scene as? UIWindowScene) else { return }
self.scene(scene, openURLContexts: connectionOptions.urlContexts)
}
but this dont work.
Hope someone can help me.
Upvotes: 4
Views: 1064
Reputation: 143
Finally I solved my problem.
I had to add a line in scene willConnectTo.. function:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let _ = (scene as? UIWindowScene) else { return }
if let url = connectionOptions.urlContexts.first?.url {
UIApplication.shared.open(url)
self.scene(scene, openURLContexts: connectionOptions.urlContexts)
}
}
Upvotes: 2