Swift4解析JSON图片遇Encodable/Decodable协议兼容错误求解决方案
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
.pngor.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
imagefield is being decoded correctly: Print thefetchedProduct.imagevalue 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
NSAppTransportSecurityexception inInfo.plistif needed for HTTP URLs).
内容的提问来源于stack exchange,提问作者pillarman38

