ios 小部件链接正常工作,但不执行任何操作

smdnsysy  于 2022-12-15  发布在  iOS
关注(0)|答案(1)|浏览(91)

我有一个带链接的小部件。我在SceneDelegate中实现小部件URL。问题是当我点击小部件时,我得到一个链接,它工作。但当我在SceneDelegate中调用视图控制器函数时,它什么也不做。嗯,它可以打印一些东西,但它不会改变任何东西。SceneDelegate

// App launched
   func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        
        guard let windowScene = (scene as? UIWindowScene) else { return }
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = ViewController()
        self.window = window
        window.makeKeyAndVisible()
        getURL(urlContext: connectionOptions.urlContexts)
    }
    
    // App opened from background
    func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        getURL(urlContext: URLContexts) 
    }
    
    // Get URL
    private func getURL(urlContext: Set<UIOpenURLContext>) {
        guard let urlContexts = urlContext.first(where: { $0.url.scheme == "app-deeplink" }) else { return }
        print(urlContexts.url)
        print("success")
        let viewController = ViewController()
        viewController.cameFromWidget()
    }

ViewController中更改标签文本的函数:

func cameFromWidget() {
        label.text = "Hello"
        print(label.text)
    }

小部件扩展名:

var body: some View {
        Text(entry.date, style: .time)
            .widgetURL(URL(string: "app-deeplink://app"))
    }

所以ViewController func只是打印文本,但当我从SceneDelegate调用它时,它不会改变。我的小部件链接只在WidgetExtension和SceneDelegate中,我没有将它添加到infoPlist中。
我的问题:为什么它能工作却什么也不做?也许我应该把它添加到某个文件中?非常感谢!

hyrbngr7

hyrbngr71#

我发现了。要在viewController中做一些更改,您需要使用rootViewController:

private func getURL(urlContext: Set<UIOpenURLContext>) {
        guard let urlContexts = urlContext.first(where: { $0.url.scheme == "app-deeplink" }) else { return }
        print(urlContexts.url)
        print("success")
        let rootViewController = window?.rootViewController as? ViewController
        rootViewController?.cameFromWidget()
    }

相关问题