ios – Swift 5 open common hyperlink in WebView from SceneDelegate


I’ve an app that may be open by way of common hyperlinks (from emails, chats, and so forth.).
When the app is open in background my code works as anticipated.

If the app is closed I can not cross the URL to my ViewController to open it in a WebView.
I am attempting to keep away from the timeout workaround within the code beneath.

I’ve tried to get it by way of shared variable universalLink in my ViewController however 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, choices connectionOptions: UIScene.ConnectionOptions) {
        
        // Common hyperlink clicked when app was closed
        for userActivity in connectionOptions.userActivities {
          if let universalLink = userActivity.webpageURL {
            // Workaround that I wish to keep away from:
            DispatchQueue.predominant.asyncAfter(deadline: .now() + 2.0) {
                self.openUniversalLink(userActivity: userActivity)
            }
          }
        }
        
        guard let _ = (scene as? UIWindowScene) else { return }
        Self.shared = self
    }

    // Common hyperlink clicked when the app is open in background (works positive).
    func scene(_ scene: UIScene, proceed 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.Title("updateWebView")
        NotificationCenter.default.publish(identify: notificationName, object: nil, userInfo: appURL)
    }
    
}

Leave a Reply