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

SwiftUI调用其他Xcode项目中Common-Currency.json文件报错求助

解决“无法在主Bundle中找到Common-Currency.json”的问题

你的代码用Bundle.main只能访问当前主项目的资源文件,而目标JSON在另一个Xcode项目里,得按以下步骤处理:

  • 把包含JSON的项目设为当前项目的依赖
    打开当前项目,选择File > Add Local...(如果是本地项目),选中包含Common-Currency.json的项目添加进来。接着去当前项目的Target > Build Phases > Link Binary With Libraries里,确认已经添加了依赖项目的框架/库。

  • 获取依赖项目的Bundle
    别再用Bundle.main,要获取依赖项目对应的Bundle。有两种实用方式:

    1. 硬编码Bundle标识符:去依赖项目的Target > Info > Bundle Identifier里找到它的标识符(比如com.example.CommonCurrency),用Bundle(identifier: "标识符")获取。
    2. 通过依赖项目里的类获取:如果依赖项目里有任意类(比如CurrencyHelper),用Bundle(for: CurrencyHelper.self)获取,这种方式不用硬编码,更灵活。
  • 修改load函数代码
    替换原来的Bundle获取逻辑,下面是两种方式的示例:

方式1:用Bundle标识符

func load<T: Decodable>(_ filename: String) -> T {
    let data: Data
    
    // 替换成你依赖项目的实际Bundle标识符
    guard let targetBundle = Bundle(identifier: "com.example.CommonCurrency"),
          let file = targetBundle.url(forResource: filename, withExtension: nil)
    else {
        fatalError("Couldn't find \(filename) in the target bundle.")
    }

    do {
        data = try Data(contentsOf: file)
    } catch {
        fatalError("Couldn't load \(filename) from the target bundle:\n\(error)")
    }

    do {
        let decoder = JSONDecoder()
        return try decoder.decode(T.self, from: data)
    } catch {
        fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
    }
}

方式2:用依赖项目中的类

// 假设依赖项目里有个名为CurrencyHelper的类
func load<T: Decodable>(_ filename: String) -> T {
    let data: Data
    
    guard let file = Bundle(for: CurrencyHelper.self).url(forResource: filename, withExtension: nil)
    else {
        fatalError("Couldn't find \(filename) in the target bundle.")
    }

    do {
        data = try Data(contentsOf: file)
    } catch {
        fatalError("Couldn't load \(filename) from the target bundle:\n\(error)")
    }

    do {
        let decoder = JSONDecoder()
        return try decoder.decode(T.self, from: data)
    } catch {
        fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
    }
}
  • 检查依赖项目的JSON配置
    去依赖项目里选中Common-Currency.json,看右侧File Inspector的Target Membership,确保勾选了对应的框架/库目标,不然文件不会被打包到Bundle里。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 15:52:43