首页 > 解决方案 > 如何在 swift 4.0 中读取 UIWebView 的响应或输出?stringByEvaluatingJavaScript(from:) 有多少种不同的方法

问题描述

我在 UIWbView 中打开一个 URL,用户可以在其中输入 OTP,提交后将提供以下响应:

{"success":true,""message":支付成功"}

我希望如果success的值为true,我将从 superview 中删除 UIWebView 。

我不知道如何读取 UIWebView 的响应。

标签: swiftxcodeuiwebviewuiwebviewdelegate

解决方案


我尝试了字符串的数量作为参数,stringByEvaluatingJavaScript(from:)但最后我通过传递"document.body.innerHTML".

"document.getElementById('someElement').innerText"如果要从 HTML 元素/组件(如文本字段等)读取数据,可以使用,。

func webViewDidFinishLoad(_ webView: UIWebView) {
        print("WebView did finish load...")
        if !webView.isLoading {
            Loader.hideLoading()
        }
        let str = webView.stringByEvaluatingJavaScript(from: "document.body.innerHTML")
        if (str?.contains("\"success\":true"))! {
            print("Success is true")
            self.viewForWebView.removeFromSuperview()
        }else {
            print("Success is false or not found")
        }
    }

推荐阅读