【发布时间】:2019-01-06 09:18:26
【问题描述】:
在我的 wkwebview 中,我有一个指向某些文件的链接,例如页面、数字等。我看到 wknavigationresponse 决定策略来决定下载或显示内容。但是 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) 决定策略: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,它可能被缓存在设备的某处)
【问题讨论】:
-
我并没有真正得到你想要实现的目标,但我在
navigationResponse.response.url中得到了一个正常的 URL。实际上我请求了 ""sarvepalli.net/ax/Subscriptions%20Data.numbers"" 并检索了Optional(https://www.sarvepalli.net/ax/Subscriptions%20Data.numbers)这似乎是你需要的,对吧?所以,我有正确的网址。 -
顺便说一句,
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView?的 if 语句中不需要这两个条件。如果您只使用if let url = navigationAction.request.url { ... }会更干净,那么您也可以在其中使用url,如果您在创建URLRequest 时无需强制解包navigationAction.request.url!。 -
对不起,如果我问的不清楚。我想使用导航响应来决定如何处理不同的 mime/type 内容。但为了使用异步 urlsession 保存它 - 我需要提供 wkwebview 无法呈现的 mimetype 的完整 URL!