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

Swift4解析JSON图片遇Encodable/Decodable协议兼容错误求解决方案

Fixing Your Swift Data Fetch & Image Loading Issues

Hey there, let's break down your problem and fix it step by step!

First: Resolve the Encodable/Decodable Protocol Errors

The error messages you're seeing ("Type 'ViewController.Class' does not conform to protocol 'Encodable'/'Decodable'") suggest you're accidentally trying to use your ViewController class as the model for parsing JSON data—which isn't the right approach. Instead, you need to create a dedicated data model struct that conforms to the Codable protocol (which combines both Encodable and Decodable).

Here's how to define a proper model for your JSON:

struct Product: Codable {
    let id: String
    let p_name: String
    let image: String
    // Add your other fields here: price, video, etc.
}

When you fetch data from your database, use this Product struct to decode the JSON response instead of your ViewController. This will immediately resolve the protocol conformance errors.

Second: Load the Image into updateImage UIImageView

Now that you can correctly decode the image string from your JSON, let's get that image into your UIImageView. The approach depends on whether the image value is a local asset name or a remote URL:

Case 1: Image is a Local Asset (in your app bundle/Assets.xcassets)

If the image string is the name of an image file in your project (like "item_one.png"), use this code:

// Assuming you've already decoded a Product instance called `fetchedProduct`
if let productImage = UIImage(named: fetchedProduct.image) {
    updateImage.image = productImage
} else {
    // Handle missing image (e.g., set a placeholder)
    print("Couldn't find image with name: \(fetchedProduct.image)")
    updateImage.image = UIImage(named: "placeholder_image")
}

Pro tip: Double-check that the image filename in your JSON matches exactly with the file in your project (including file extensions like .png or .jpg), and that the image is added to your app's target.

Case 2: Image is a Remote URL

If the image string is a full URL (like "https://example.com/item_one.png"), you'll need to fetch it asynchronously using URLSession:

// Assuming you've decoded `fetchedProduct`
guard let imageURL = URL(string: fetchedProduct.image) else {
    print("Invalid image URL: \(fetchedProduct.image)")
    updateImage.image = UIImage(named: "placeholder_image")
    return
}

// Fetch the image data
URLSession.shared.dataTask(with: imageURL) { data, _, error in
    if let error = error {
        print("Failed to load image: \(error.localizedDescription)")
        DispatchQueue.main.async {
            updateImage.image = UIImage(named: "placeholder_image")
        }
        return
    }
    
    // Convert data to UIImage and update the UI (must run on main thread)
    if let imageData = data, let loadedImage = UIImage(data: imageData) {
        DispatchQueue.main.async {
            updateImage.image = loadedImage
        }
    }
}.resume()

Quick Troubleshooting Checks

  • Verify that your JSON's image field is being decoded correctly: Print the fetchedProduct.image value to confirm it's not empty or malformed.
  • If using local images, ensure the image file is included in your project's "Copy Bundle Resources" build phase.
  • If loading remote images, make sure your app has permission to access the internet (add the NSAppTransportSecurity exception in Info.plist if needed for HTTP URLs).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:39:11