从 WKWebView 获取 JSON 文本 [英] Get JSON text from WKWebView

查看:70
本文介绍了从 WKWebView 获取 JSON 文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆