'iOS Deep Link from Widget when App closed?

My widget has several links that the user can click, the link are set up as follows:

Link(destination: URL(string: "widget://start")!)

Now I am able to detect the press in the scene delegate with the following function:

    func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    if let item = URLContexts.first {
        UserDefaults.standard.set(item.url.absoluteString, forKey: "URL")
        print(item.url)
        print(URLContexts)
    }
}

However, that doesn't work when the app is closed. I tried putting this block of code everywhere, scene delegate, app delegate, but I just can't find a solution on how to detect the tap when the app is closed. Is there a way to do that?



Solution 1:[1]

Add this

  func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        
        guard let _ = (scene as? UIWindowScene) else { return }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            if let item = connectionOptions.urlContexts.first {
                UserDefaults.standard.set(item.url.absoluteString, forKey: "URL")
                print(item.url)
                print(URLContexts)
            }
        }
    }

For those, who use only AppDelegate

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        if let userActDic = launchOptions?[UIApplication.LaunchOptionsKey.userActivityDictionary] as? [String: Any],
           let userActivity  = userActDic["UIApplicationLaunchOptionsUserActivityKey"] as? NSUserActivity {
            // Do with user activity
        }
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1