在我的 wkwebview 中,我有一个指向某些文件(如页面、数字等)的链接。我看到 wknavigationresponsedecidepolicy 来决定下载或显示内容。然而,wknavigation响应对象似乎不包含请求的URL,而是苹果修改的URL。例如我请求
https://www.sarvepalli.net/ax/Subscriptions%20Data.numbers
它被翻译成 wknavigationresponse.response.url ,如下所示:
x-apple-ql-id://4A35794C-554C-4732-9159-BFCB7A688F1D/x-apple-ql-magic/Subscriptions%20Data.numbers
我厌倦了使用 wknavigationaction 设置一个名为 current_url 的全局变量,但这似乎不起作用,因为这些方法要么异步调用,要么以与我想象相反的顺序调用(1)Wknavigationaction 然后(2)decidepolicyfor:WknavigationResponse
我在寻找一种方法来收集用户单击 webview 中的链接时所请求的当前 URL 方面遇到任何帮助,我们将不胜感激。
谢谢 维杰
/* This should get replaced by the navgationaction */
var current_url= URL(string: "https://example.com/download/a.docx")!
func webView(_ webView: WKWebView,
createWebViewWith configuration: WKWebViewConfiguration,
for navigationAction: WKNavigationAction,
windowFeatures: WKWindowFeatures) -> WKWebView? {
// if navigationAction.targetFrame == nil, let url = navigationAction.request.url {
if navigationAction.request.url != nil, let url = navigationAction.request.url {
//if url.description.lowercased().range(of: "http://") != nil ||
self.current_url = url
let url_request:URLRequest = URLRequest(url: navigationAction.request.url!)
webView.load(url_request)
}
func webView(_ webView: WKWebView,
decidePolicyFor navigationResponse: WKNavigationResponse,
decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
let mimetype = navigationResponse.response.mimeType!
let thisurl = navigationResponse.response.url?.absoluteString
print("Current Url being requested is ",current_url.absoluteString)
print("Current Url being considered ", navigationResponse.response.url?.absoluteString ?? "unknown");
decisionHandler(.allow)
}
我得到了奇怪的回应,例如
当前请求的 URL 打印为“https://example.com/download/a.docx ” (这实际上应该是被单击的 URL,即 https://www.sarvepalli.net/ax/Subscriptions%20Data.numbers )
正在考虑当前网址 x-apple-ql-id://4A35794C-554C-4732-9159-BFCB7A688F1D/x-apple-ql-magic/Subscriptions%20Data.numbers (这是苹果指定的不可用的内部 URL,可能被缓存在设备中的某处)
最佳答案
我解决了这个问题。看起来如果我强制进行 navigationpolicy 查找,那么每次都会调用此 wkwebview 委托(delegate),并且一切都像我预期的那样正常工作。
func webView(_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
// if navigationAction.targetFrame == nil, let url = navigationAction.request.url {
if navigationAction.request.url != nil, let url = navigationAction.request.url {
self.curl = url
decisionHandler(.allow)
}
}
现在 self.curl 全局变量会随着每次 URL 调用而更新。
谢谢! 维杰
关于ios - WKwbview navigationresponse如何获取请求的URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54055405/