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>
4 Réponses :
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.
@Mortiz bien sûr, mis à jour avec Swift. j'espère que ce sera utile
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!)
}
}
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 {}}
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)
}
}
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)
})
}
Copie possible de Swift Retrieve HTML data from Webview
@Kuldeep, avez-vous vérifié avec OP s'il utilise
UIWebViewouWKWebView?