首页 > 解决方案 > Swift 从今天扩展中的按钮打开特定的视图控制器

问题描述

我试图在今天的扩展中单击按钮打开特定的视图控制器,但无法显示它。主应用程序使用 url 方案在主根控制器上正确打开,但不是我在 App Delegate 中设置的特定视图控制器。

我尝试了所有可以在 Google 上找到的教程和答案,例如: How to open specific View controller on Widgets/Today Extension click

但我无法让它工作。我试图找出问题出在哪里,我认为应用程序委托中的方法没有调用。我写了一些 print() 方法,但没有一个出现在控制台中。我已经像上面链接的答案一样正确配置了 URL 方案,所以我不知道为什么 App Delegate 中的方法不执行。

希望有人有小费我还能尝试什么。

TodayViewController 中 Button IBAction 的代码:

    @IBAction func addButtonOnePressed(_ sender: UIButton) {
        let url = URL(string: "OpenURL://")!
        self.extensionContext?.open(url, completionHandler: nil)
    }
    

来自 App Delegate Method 的代码(我尝试了所有我能找到的):

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool
    {
        if url.scheme == "OpenURL"
        {

                let storyboard = UIStoryboard(name: "Groups", bundle: nil)
                let vc = storyboard.instantiateViewController(withIdentifier: "Group") as! MasterViewController
                self.window?.rootViewController = vc
                self.window?.makeKeyAndVisible()
     
        }
        return true
    }

更新: 我自己解决了。我必须在 SceneDelegate 中而不是在 AppDelegate 中完成所有工作,并负责 Tabbar 控制器和导航控制器。

SceneDelegate.swift 中的新代码:

    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: "Group") as? MasterViewController,
            let tabBarController = rootViewController as? UITabBarController,
            let navController = tabBarController.selectedViewController as? UINavigationController {
                navController.pushViewController(rootVC, animated: true)
                }
            }
        }
    }

标签: iosswifttoday-extension

解决方案


推荐阅读