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

SwiftUI从JSON加载图片失败:资产目录未找到对应图片

解决SwiftUI加载JSON指定路径图片失败的问题

问题根源

你当前使用的Image(property.thumbnailName)初始化方法默认从Assets.xcassets资源目录加载图片,但JSON中指定的是文件系统路径,且图片未被正确配置到项目资源中,导致App找不到对应图片。

解决方案

方案1:使用Asset Catalog管理图片(推荐)

  1. 打开项目的Assets.xcassets,右键选择New Folder,命名为PropertyResources
  2. 将所有图片(含缩略图)拖入该文件夹,确保图片名称与JSON中去掉PropertyResources/前缀后的名称完全一致(例如JSON中PropertyResources/thumbnail_house1.jpeg对应图片命名为thumbnail_house1.jpeg)
  3. 修改JSON文件,移除所有路径前缀:
    // 原内容
    "thumbnailName": "PropertyResources/thumbnail_house1.jpeg"
    // 修改后
    "thumbnailName": "thumbnail_house1.jpeg"
    
  4. 保持原有Image(property.thumbnailName)代码即可,此时会自动从Asset Catalog加载图片

方案2:保留文件夹路径加载图片

若需保留原路径结构,可将图片作为文件夹资源添加到项目:

  1. 在项目中右键选择New Group with Folder,选择存放图片的PropertyResources文件夹,勾选Create folder references(不要选Create groups)
  2. 确认该文件夹已添加到项目的Target -> Build Phases -> Copy Bundle Resources中,确保打包时会被复制到App Bundle
  3. 修改PropertyRow中的图片加载逻辑,改用Bundle文件路径加载:
    struct PropertyRow: View {
        let property: Property
        
        var body: some View {
            HStack {
                // 替换原Image代码
                if let imageName = property.thumbnailName.components(separatedBy: "/").last,
                   let imageUrl = Bundle.main.url(forResource: imageName.deletingPathExtension(), withExtension: imageName.pathExtension) {
                    Image(uiImage: UIImage(contentsOfFile: imageUrl.path)!)
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                        .frame(width: 80, height: 80)
                        .cornerRadius(8)
                } else {
                    // 加载失败时的占位图
                    Image(systemName: "photo")
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                        .frame(width: 80, height: 80)
                        .cornerRadius(8)
                        .foregroundColor(.gray)
                }
                
                // 其余代码保持不变
                VStack(alignment: .leading) {
                    Text(property.address)
                        .font(.headline)
                    Text("Type: \(property.type)")
                        .font(.subheadline)
                    Text("Price: \(property.price)")
                        .font(.subheadline)
                }
                .padding(.leading, 8)
                
                Spacer()
            }
            .padding()
        }
    }
    

额外优化建议

  • 修复JSON加载路径:当前loadData使用硬编码绝对路径,发布版会失效,建议将JSON添加到项目资源,改用Bundle加载:
    private func loadData() {
        guard let fileURL = Bundle.main.url(forResource: "properties", withExtension: "json") else {
            print("JSON文件未找到")
            return
        }
        do {
            let data = try Data(contentsOf: fileURL)
            properties = try JSONDecoder().decode([Property].self, from: data)
        } catch {
            print("加载数据出错: \(error)")
        }
    }
    
  • 文件名一致性检查:确保JSON中的文件名(含大小写、后缀)与实际图片完全匹配,iOS文件系统区分大小写

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 11:07:31