You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift通过evaluateScript将JSON对象传入WKWebView的JavaScript函数

嘿,我来帮你把Swift里的JSON数据顺畅传给WKWebView的JavaScript函数!你已经搞定了读取文件转JSON的第一步,接下来用evaluateJavaScript就能实现需求,下面是具体的实现方案和代码示例:

实现步骤与完整代码

1. Swift侧核心逻辑实现

首先我们把读取文件转JSON的函数写好,然后在WKWebView页面加载完成后,把JSON数据传给JS函数。这里提供两种传参方式,你可以根据需求选择:

import WebKit

class ViewController: UIViewController, WKNavigationDelegate {
    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 初始化WKWebView
        let webConfig = WKWebViewConfiguration()
        webView = WKWebView(frame: view.bounds, configuration: webConfig)
        webView.navigationDelegate = self
        view.addSubview(webView)
        
        // 加载本地HTML页面(也可以换成远程URL)
        if let htmlPath = Bundle.main.path(forResource: "index", ofType: "html") {
            let htmlUrl = URL(fileURLWithPath: htmlPath)
            webView.loadFileURL(htmlUrl, allowingReadAccessTo: htmlUrl.deletingLastPathComponent())
        }
    }
    
    // 读取本地JSON文件并转为Swift JSON对象
    func loadLocalJson() -> [String: Any]? {
        guard let filePath = Bundle.main.path(forResource: "data", ofType: "json") else {
            print("找不到目标JSON文件")
            return nil
        }
        
        do {
            let fileData = try Data(contentsOf: URL(fileURLWithPath: filePath))
            return try JSONSerialization.jsonObject(with: fileData, options: []) as? [String: Any]
        } catch {
            print("JSON解析失败:\(error.localizedDescription)")
            return nil
        }
    }
    
    // 页面加载完成后,传递JSON给JS
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        guard let jsonObj = loadLocalJson() else { return }
        
        // 方式1:把Swift JSON对象转成JSON字符串,传给JS解析
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: jsonObj, options: .prettyPrinted)
            if let jsonStr = String(data: jsonData, encoding: .utf8) {
                // 调用JS的receiveSwiftData函数
                webView.evaluateJavaScript("receiveSwiftData(\(jsonStr))") { result, error in
                    if let err = error {
                        print("调用JS函数出错:\(err.localizedDescription)")
                    }
                }
            }
        } catch {
            print("JSON转字符串失败:\(error.localizedDescription)")
        }
        
        // 方式2:直接传Swift JSON对象(WKWebView会自动转为JS可识别的对象)
        webView.evaluateJavaScript("receiveSwiftData(\(jsonObj))") { result, error in
            if let err = error {
                print("调用JS函数出错:\(err.localizedDescription)")
            }
        }
    }
}

2. 配套的JavaScript代码(本地index.html)

在你的HTML文件里定义好接收数据的JS函数,就能直接拿到Swift传过来的JSON数据了:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Swift-JS交互测试</title>
</head>
<body>
    <script>
        function receiveSwiftData(data) {
            console.log("收到来自Swift的JSON数据:", data);
            // 直接访问数据属性,比如 data.username、data.age
            if (data.username) {
                console.log("用户名:", data.username);
            }
        }
    </script>
</body>
</html>

几个关键注意事项

  • 确保你的data.json文件已经添加到Xcode项目中,并且勾选了对应的target,不然会出现找不到文件的问题。
  • 如果你的JSON是数组类型(比如[Any]),只需要把Swift函数的返回类型改成[Any]?,JS里同样可以直接遍历数组。
  • 一定要在didFinish代理方法里调用evaluateJavaScript,确保页面加载完成、JS函数已经存在,不然会出现调用失败的情况。

内容的提问来源于stack exchange,提问作者Abi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:26:16