1
votes

Comment analyser les données de webView à utiliser dans le code

J'ai un WKWebView dans mon projet qui effectue certaines opérations, après avoir cliqué sur Soumettre dans WKWebView , il affiche les données JSON en javaScript dont j'ai besoin pour analyser mon code.

/ p>


2 commentaires

Copie possible de Swift Retrieve HTML data from Webview


@Kuldeep, avez-vous vérifié avec OP s'il utilise UIWebView ou WKWebView ?


4 Réponses :


0
votes

Vous pouvez obtenir les données HTML sous forme de chaîne en utilisant ce morceau de code

en Objectif C

let yourWebView = UIWebView();
let html : String = yourWebView.stringByEvaluatingJavaScript(from: "document.body.innerHTML") ?? "";

dans Swift

NSString *html = [yourWebView stringByEvaluatingJavaScriptFromString: @"document.body.innerHTML"];

Vous devez analyser ce que vous avez reçu et traiter ultérieurement en conséquence.

Dans votre cas, vous pourriez obtenir le json complet dans la chaîne.


1 commentaires

@Mortiz bien sûr, mis à jour avec Swift. j'espère que ce sera utile



0
votes

Vous pouvez obtenir le code source de votre UIWebViewpage.

func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
    webView.evaluateJavaScript("document.getElementsByTagName('html')[0].innerHTML") { innerHTML, error in
        print(innerHTML!)
    }
}


1 commentaires

cela a fonctionné avec moi , func webView (webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {do {let content = try String (contentsOf: webView.url!) if let data = content.data (using: String.Encoding .utf8) {let obj = essayez JSONSerialization.jsonObject (avec: data, options: []) comme? [String: Any]} catch {}}



1
votes

votre JSON est livré dans la balise body, puis utilisez ce code ou changez du côté Web pour donner JSON dans la balise body

if let html = webView.stringByEvaluatingJavaScript(from: "document.body.innerHTML"){

            let data = html.data(using: .utf8)!
            do {
                if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? Dictionary<String,Any>
                {
                    print(jsonArray) // use the json here
                } else {
                    print("bad json")
                }
            } catch let error as NSError {
                print(error)
            }
        }


0 commentaires

0
votes

Exemples Swift 5.1:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("redirect didFinish")
        print(webView)
        webView.evaluateJavaScript("document.documentElement.outerHTML.toString()",
                                   completionHandler: { (html: Any?, error: Error?) in
                                    print(html as Any)
        })
    }


0 commentaires