SwiftUI从JSON加载图片失败:资产目录未找到对应图片
解决SwiftUI加载JSON指定路径图片失败的问题
问题根源
你当前使用的Image(property.thumbnailName)初始化方法默认从Assets.xcassets资源目录加载图片,但JSON中指定的是文件系统路径,且图片未被正确配置到项目资源中,导致App找不到对应图片。
解决方案
方案1:使用Asset Catalog管理图片(推荐)
- 打开项目的
Assets.xcassets,右键选择New Folder,命名为PropertyResources - 将所有图片(含缩略图)拖入该文件夹,确保图片名称与JSON中去掉
PropertyResources/前缀后的名称完全一致(例如JSON中PropertyResources/thumbnail_house1.jpeg对应图片命名为thumbnail_house1.jpeg) - 修改JSON文件,移除所有路径前缀:
// 原内容 "thumbnailName": "PropertyResources/thumbnail_house1.jpeg" // 修改后 "thumbnailName": "thumbnail_house1.jpeg" - 保持原有
Image(property.thumbnailName)代码即可,此时会自动从Asset Catalog加载图片
方案2:保留文件夹路径加载图片
若需保留原路径结构,可将图片作为文件夹资源添加到项目:
- 在项目中右键选择New Group with Folder,选择存放图片的
PropertyResources文件夹,勾选Create folder references(不要选Create groups) - 确认该文件夹已添加到项目的Target -> Build Phases -> Copy Bundle Resources中,确保打包时会被复制到App Bundle
- 修改
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
相关产品推荐
相关产品推荐

