Search code examples
iosswiftswiftuiios14widgetkit

Widget link works but does nothing


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 }
      
        let viewController = ViewController()
        viewController.widgetTapped()
    }

Function in ViewController that changes labels text:

func widgetTapped() {
        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!


Solution

  • 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 }
     
            let rootViewController = window?.rootViewController as? ViewController
            rootViewController?.widgetTapped()
        }