ios Webview通用链接加载URL

1qczuiv0  于 2023-08-08  发布在  iOS
关注(0)|答案(1)|浏览(132)

所以在使用某个用例时遇到了一些麻烦。
我为iOS创建了一个使用WebView的应用程序。一切都工作得很好,我能够成功地配置通用链接。它提示在应用程序中打开,因为它应该。
问题是我设置的触发应用程序的URL路径,没有传递到应用程序。
因此,应用程序打开,但它只在主页上打开,如果它还没有被打开,或者它打开到最后一个位置。
我相信这与它的webview有关,它需要加载触发它的相同URL,以便它可以转到路径。
示例:URL为https://testapp.com/path
但在WebView应用程序中,如果尚未打开它,它只会转到https://testapp.com(主页)
或者https://testapp.com/lastlocation,如果它被打开,这是它的最后一个位置。
我试着用下面的方法设置应用程序代表,但没有成功。

func application(_ application: UIApplication, continue userActivity: NSUserActivity,
                     restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) ->
                        Bool {
        guard let url = userActivity.webpageURL else{return false}
        guard let component = URLComponents(string: url.absoluteString) else {return false}
        

        return true
    }

字符串

kxkpmulp

kxkpmulp1#

感谢rudedog。下面是我根据这个建议所做的工作。
将以下内容添加到触发通用链接的应用程序委托

应用委托

var universalLinkURL: String = ""

func application(_: UIApplication, continue userActivity: NSUserActivity, restorationHandler _: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
    guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,
        let url = userActivity.webpageURL else {
        print(universalLinkURL)
        return false
    }
    let universalURL = url.absoluteString
    universalLinkURL = universalURL
    print(universalURL, universalLinkURL)
    return true
}

字符串
然后在视图控制器中,我在viewDidLoad中添加了这些代码用于初始启动应用程序,并在appDidBecomeActive下添加了这些代码,因此如果应用程序打开,它会正确处理通用链接。

函数viewDidLoad函数appDidBecomeActive

//Get the url from AppDelegate here
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let universalurl = appDelegate.universalLinkURL
    
    if (!universalurl.isEmpty)
    {
        let urluniversal = URL(string: universalurl)
        webView.load(URLRequest(url: urluniversal!))
    }


最后,为了避免变量总是触发加载,如果你关闭应用程序,把它放在后台,等等。我正在清除下面的函数中的变量应用委托

applicationWillResignActive、applicationDidEnterBackground、applicationWillEnterForeground

universalLinkURL = ""


希望这能帮助任何人,如果他们遇到类似的情况!

相关问题