首页 > 解决方案 > 单击通用链接在我的应用程序中打开 WKWebView

问题描述

我在 Swift 4 中创建了一个自制的 PWA 应用程序来浏览我的网站,其中包含一些选项,例如 Firebase 和
当我的网站在 Safari 中打开或当用户单击朋友共享的通用链接时通知我需要打开我的应用程序。
我正确设置了我的网站 apple-app-site-association并且它可以工作,当我在 Safari 中打开相对 url 时,它会向我显示打开我的应用程序的提示。
但问题是,当我在 Safari 中出现提示之间打开我的应用程序时尝试处理通用链接时,我尝试使用它(正如 Apple 文档所说的通用链接

func application(_ application: UIApplication,
          continue userActivity: NSUserActivity,
          restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool{

要更改我的 WKWebView,我使用了基于答案的代码。这是我在更改 WebView url
中的 AppDelegate 代码:func continue

if(userActivity.webpageURL != nil){
    g_url = userActivity.webpageURL // g_url is declared at top as 'var g_url: URL?'
    let notificationName = NSNotification.Name(rawValue: "updateUrl")
    NotificationCenter.default.post(name: notificationName, object: nil)
    return true
}else{
    return false
}

这是在 ViewController 中设置 url 的代码:

let appDelegate = UIApplication.shared.delegate as! AppDelegate
url = appDelegate.g_url

let notificationName = Notification.Name("updateUrl")
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.updateUrl), name: notificationName, object: nil)

updateUrl()


updateUrl: @objc 函数 updateUrl(){

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    if(appDelegate.g_url != nil){
        url = appDelegate.g_url!
    }else{
        url = URL(string: "https://my.Site/Home")!
    }
    let request = URLRequest(url: url)
    MyWebView.load(request)

    MyWebView.navigationDelegate = self

当 Safari 调用应用程序时,WebView 页面是最后一个打开的页面,如果是第一次打开,则为“主页”。
我需要了解我是否错过了某些东西,或者我是否应该使用其他东西来制作这个

标签: iosswift4wkwebviewxcode11ios-universal-links

解决方案


由于 IOS 13 的最新更新,该代码无法正常工作。AppDelegate中的continue函数没有被调用,但在SceneDelegate中添加continue函数可以正常工作。我使用旧模式获得 url 参数(仅适用于一个场景):

private(set) static var shared: SceneDelegate?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let _ = (scene as? UIWindowScene) else { return }
    Self.shared = self
}

在我设置的 ViewController 代码中

let appDelegate = SceneDelegate.shared?.g_url

获取变量和这个观察者来调用改变

let notificationName = Notification.Name("updateUrl")
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.updateUrl), name: notificationName, object: nil)

推荐阅读