简体   繁体   中英

Widget link works but doesn't do anything

I have a widget with a link. I'm implementing the widget URL in SceneDelegate . The problem is when I tap on the widget I get a link, it works. But when I call View Controller function in SceneDelegate , it does nothing. Well, it can print something, but it doesn't change anything. 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()
    }

Function in ViewController that changes labels text:

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

WidgetExtension:

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

So ViewController func just prints the text but doesn't change it when I call it from SceneDelegate . My widget link is only in WidgetExtension and SceneDelegate, I didn't add it to infoPlist.

My question: Why does it work but does nothing? Maybe I should add it to some file? Thank you so much!

I found out. To make some changes in your viewController you need to make it with 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()
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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