在我的wkwebview中,我有一个指向页面,数字等文件的链接。我看到wknavigationresponse的Decisionpolicy决定下载或显示内容。但是,wknavigation响应对象似乎不包含请求的URL,而是包含Apple修改的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)decisionpolicyfor:WknavigationResponse
当用户单击Web视图中的链接时,我在寻找一种方法来收集当前请求的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)
}
我收到类似
的奇怪回复正在请求的当前网址打印为“ 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 (这是Apple指定的不可用的内部URL,可能已缓存在设备中的某个位置)
答案 0 :(得分:0)
我解决了这个问题。看起来,如果我强制进行Navigationpolicy查找,则每次都会调用此wkwebview委托,并且一切正常,就像我期望的那样。
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时,全局变量都会更新。
谢谢! 维杰