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

iOS Swift调用Tronweb.js时检测库加载状态及版本获取异常问题

iOS Swift 集成 Tronweb.js 加载校验失败修复方案

核心原因

  • Tronweb 实例化存在异步逻辑,执行 JS 加载代码后立即读取属性,实例尚未完成全局挂载,因此返回 undefined
  • objectForKeyedSubscript 仅支持读取全局作用域下的顶层属性,直接传入 tronweb.version.api 嵌套路径无法正确识别,需逐层读取或通过 evaluateScript 执行嵌套属性读取语句

修复后代码

do {
    guard let jsContext = jsContext else {
        print("JS 上下文未初始化")
        return
    }
    // 注入全局错误捕获,排查 JS 执行异常
    jsContext.evaluateScript("""
    window.onerror = function(message, source, lineno) {
        console.log('JS 执行报错: ' + message + ' 行号: ' + lineno);
        return true;
    }
    """)
    // 加载 Tronweb 核心 JS
    let TronWebJS = try String(contentsOf: Bundle.main.url(forResource: "TronWeb", withExtension: "js")!, encoding: .utf8)
    let tronwebEvalRes = jsContext.evaluateScript(TronWebJS)
    if tronwebEvalRes?.isError == true {
        print("Tronweb JS 执行失败: \(tronwebEvalRes!.toString()!)")
        return
    }
    // 延迟等待初始化完成,可替换为 JS 回调通知原生的方案提升精准度
    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        // 读取版本校验加载状态
        let apiVersion = jsContext.evaluateScript("tronweb?.version?.api ?? 'uninitialized'")?.toString() ?? "uninitialized"
        print("Tronweb API 版本: \(apiVersion)")
        
        guard apiVersion != "uninitialized" else {
            print("Tronweb 加载失败,实例未完成挂载")
            return
        }
        // 校验通过后再执行 trxSendTest.js
        do {
            let trxSendTest = try String(contentsOf: Bundle.main.url(forResource: "trxSendTest", withExtension: "js")!, encoding: .utf8)
            jsContext.evaluateScript(trxSendTest)
        } catch {
            print("trxSendTest.js 读取失败: \(error)")
        }
    }
} catch {
    print("本地 JS 文件读取失败: \(error)")
}

优化建议

固定延迟的方案受设备性能影响较大,可在 Tronweb.js 末尾添加初始化完成回调,通过 JSExport 桥接协议直接通知原生,无需硬编码等待时长,校验逻辑更稳定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 10:39:02