Swift 5 open universal link in WebView from SceneDelegate

Viewed 15

I have an app that can be open via universal links (from emails, chats, etc.). When the app is open in background my code works as expected.

If the app is closed I can't pass the URL to my ViewController to open it in a WebView. I'm trying to avoid the timeout workaround in the code below.

I've tried to get it via shared variable universalLink in my ViewController but I get a nil:

let universalLink = SceneDelegate.shared?.universalLink

SceneDelegate:

import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    static var shared: SceneDelegate?
    var universalLink: URL?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        
        // Universal link clicked when app was closed
        for userActivity in connectionOptions.userActivities {
          if let universalLink = userActivity.webpageURL {
            // Workaround that I want to avoid:
            DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                self.openUniversalLink(userActivity: userActivity)
            }
          }
        }
        
        guard let _ = (scene as? UIWindowScene) else { return }
        Self.shared = self
    }

    // Universal link clicked when the app is open in background (works fine).
    func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
        openUniversalLink(userActivity: userActivity)
    }

    func openUniversalLink(userActivity: NSUserActivity)
    {
        guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,
            let universalLink = userActivity.webpageURL//,
        else {
                return
        }
        let appURL:[String: String] = ["appURL": universalLink.absoluteString]
        let notificationName = Notification.Name("updateWebView")
        NotificationCenter.default.post(name: notificationName, object: nil, userInfo: appURL)
    }
    
}
0 Answers
Related