繁体   English   中英

小部件链接有效,但不执行任何操作

[英]Widget link works but doesn't do anything

我有一个带有链接的小部件。 我正在 SceneDelegate 中实现小部件SceneDelegate 问题是当我点击小部件时,我得到一个链接,它可以工作。 但是当我在 SceneDelegate 中调用 View Controller 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 中的 Function 更改标签文本:

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。

我的问题:为什么它起作用但什么也不做? 也许我应该将它添加到某个文件中? 太感谢了!

我发现。 要在 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()
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM