Parse json object from response inside WKWebView (Swift, iOS)

Viewed 2477

I'm trying to receive json object from request inside WKWebView. For now I can only get html string from body, but it wrapped in some tags (like <pre>). How I can do it not using any third part libs? And also get body directly from response?

My code demonstrate what I have now and it doesn't provide me what I need. I'm using delegate methods of WKNavigationDelegate and evaluateJavaScript method to get inner htmlText of body

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        webView.evaluateJavaScript("document.body.innerHTML") { (anyObject, error) in
            guard let htmlStr = anyObject as? String else {
                return 
            }
            let data: Data = htmlStr.data(using: .utf8)!
            do {
                let jsObj = try JSONSerialization.jsonObject(with: data, options: .init(rawValue: 0))
                if let jsonObjDict = jsObj as? Dictionary<String, Any> {
                    let threeDSResponse = ThreeDSResponse(dict: jsonObjDict)
                    print(threeDSResponse)
                }
            } catch _ {
                print("having trouble converting it to a dictionary")
            }
        }
    }

Now I receive htmlStr as

"{\"id\":68324947,\"is_test\":false,\"status\":2,\"status_description\":\"055 - Invalid transaction\"}"

and want to get it directly as json(parse it) from

{\"id\":68324947,\"is_test\":false,\"status\":2,\"status_description\":\"055 - Invalid transaction\"}

also I can't use 3part libs and should make as much pure as It can be.

1 Answers

Use JSONDecoder

do {
    let dec = JSONDecoder()
    dec.keyDecodingStrategy = .convertFromSnakeCase
    let res = try dec.decode(Root.self, from:Data(htmlStr.utf8))
    print(res)
} catch  {
    print("having trouble converting it to a dictionary" , error)
}

struct Root : Codable {
    let id,status:Int
    let isTest:Bool
    let statusDescription:String
}
Related