快速打开主应用未打开时如何从今天的扩展中打开特定的ViewController

问题描述

我创建了带有某些UIButton的Today扩展,并且我想在用户点击按钮时打开特定的视图控制器。当主应用程序打开时,它现在可以工作,但是当主应用程序关闭时,它将仅打开主应用程序,而不导航到我的特定视图控制器。

我做了什么: 如果在 TodayExtension View Controller 中按下了按钮,我已经设置了URL Sheme并编写了OpenURL代码。

    @objc func buttonClick(sender: UIButton) {
        let tag = sender.tag
        if let url = URL(string: "OpenURL://\(tag)")
            {
                self.extensionContext?.open(url,completionHandler: nil)
            }
        }

SceneDelegate 中,我编写了用于导航到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!)
                }
            }
        }
    }

但是就像我说的那样,这仅在之前打开主应用程序时有效。 即使关闭主ap,我该怎么办才能正常工作?

在Google的帮助下,我发现必须设置func scene(_ scene: UIScene,willConnectTo session: UISceneSession,options connectionOptions: UIScene.ConnectionOptions) {函数,但是我不知道该怎么做。我写的是

    func scene(_ scene: UIScene,options connectionOptions: UIScene.ConnectionOptions) {
        guard let _ = (scene as? UIWindowScene) else { return }
        self.scene(scene,openURLContexts: connectionOptions.urlContexts)

    }

但这不起作用。

希望有人可以帮助我。

解决方法

最后我解决了我的问题。

我必须在场景willConnectTo ..函数中添加一行:

    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)

        }
    }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...