簡體   English   中英

當主應用程序未打開時,Swift 如何從今天的擴展中打開特定的視圖控制器

[英]Swift how to open specific viewcontroller from today extension when main app is not open

我用一些 UIButtons 創建了一個今天的擴展,我想在用戶點擊一個按鈕時打開一個特定的視圖控制器。 當主應用程序打開時它現在可以工作,但是當它關​​閉時它只會打開主應用程序並且不會導航到我的特定視圖控制器。

我所做的:如果在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 關閉,我該怎么做才能正常工作?

在谷歌的幫助下,我發現我必須設置func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {功能,但我不知道如何。 我寫的是

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, 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)

        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM