从 WKWebView 获取 JSON 文本 [英] Get JSON text from WKWebView
问题描述
我想从 http://www.devpowerapi.com/fingerprint 获取 http://www.devpowerapi.com/fingerprint 的内容一个 WKWebView
I want to get the contents of http://www.devpowerapi.com/fingerprint from a WKWebView
evaluateJavaScript("document.documentElement.innerHTML")
返回 而不是实际的JSON
evaluateJavaScript("document.documentElement.innerHTML")
returns <head></head><body></body>
instead of the actual JSON
是否可以使用 WKWebView 获取内容?
Is it possible to get the contents with a WKWebView?
推荐答案
最简单的方法(适用于这种特定情况):
webView.evaluateJavaScript("document.getElementsByTagName('pre')[0].innerHTML", completionHandler: { (res, error) in
if let fingerprint = res {
// Fingerprint will be a string of JSON. Parse here...
print(fingerprint)
}
})
可能更好的方法:
所以 .innerHTML
返回 HTML,而不是 JSON 标头.众所周知,使用 WKWebView
很难获取 JSON 标头,但您可以尝试使用此方法.第一组:
So .innerHTML
returns HTML, not a JSON header. JSON headers are notoriously difficult to grab with WKWebView
, but you could try this method for that. First set:
webView.navigationDelegate = self
然后在WKNavigationDelegate
方法中:
public func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
let res = navigationResponse.response as! HTTPURLResponse
let header = res.allHeaderFields
print(header)
}
这篇关于从 WKWebView 获取 JSON 文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!