swift 从JSON下载带有图像的shopItems(url)[已关闭]

plicqrtu  于 2023-03-28  发布在  Swift
关注(0)|答案(1)|浏览(164)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题?**添加详细信息并通过editing this post阐明问题。

6天前关闭。
Improve this question
我试图从服务器上下载的项目为JSON,每个项目都有一个链接(URL),它的形象。
做了编辑(读取后重新加载数据),但仍然不能按预期工作。

public class ShopModel: Codable {
    
    var latest: [ShopItem]
    var flashSale: [ShopItem]
}

struct ShopItem: Codable {
    let category: String
    let name: String
    let price: Double
    let image_url: URL
    
    var image: UIImage? {
        get async throws {
            let (data, _) = try await URLSession.shared.data(from: image_url)
            return UIImage(data: data)
        }
    }
}

我做了一个自定义的NetworkHelper来获取项目:

public class NetworkHelper {
    
    var items: [ShopItem] = []
    
    static let shared = NetworkHelper()
    
    let flashSaleURL = URL(string: "https://run.mocky.io/v3/a9ceeb6e-416d-4352-bde6-2203416576ac")
    
    
    
    func downloadLatest() async throws -> [ShopItem] {
        let latestURL = URL(string: "https://run.mocky.io/v3/cc0071a1-f06e-48fa-9e90-b1c2a61eaca7")!
        
        let (data, response) = try await URLSession.shared.data(from: latestURL)
        
        guard let httpResponse = response as? HTTPURLResponse,
              (200..<300).contains(httpResponse.statusCode) else { throw URLError(.badServerResponse) }
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        let results = try decoder.decode(ShopModel.self, from: data)
        print("items downloaded")
        return results.latest
    }
}

但是我需要在自定义UICollectionView中显示这些项目(图像)沿着它们的“名称”、“价格”和“类别”。
我试图在VC的viewWillAppear中检索这些项目,并将它们放置在CollectionView属性“单元格”类型[ShopItem]中。比collectionView的cellForItemAt检索每个单元格/项目的图像,但由于某种原因,我的项目数组为空。
一个二个一个一个
我正在寻找帮助,以了解为什么我的数组是空的,我如何才能得到预期的项目与图像。我猜,我使用异步等待错误

dfty9e19

dfty9e191#

我解决了这个问题。这个问题是由于我没有在shopItem结构中创建编码键枚举,而在shopModel结构中也是如此。这个键可以帮助解码器理解它应该如何处理获取的数据,我猜:
第一个为shopItem

enum CodingKeys: String, CodingKey {
    case category = "category"
    case name = "name"
    case price = "price"
    case image_url = "image_url"
}

init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        image_url = try values.decodeIfPresent(String.self, forKey: .image_url)
        category = try values.decodeIfPresent(String.self, forKey: .category)
        name = try values.decodeIfPresent(String.self, forKey: .name)
        price = try values.decodeIfPresent(Double.self, forKey: .price)
        
    }

第二个是shopModel:

enum CodingKeys: String, CodingKey {

        case latest = "latest"
        case flashSale = "flash_sale"
    }
    
    required public init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        latest = try values.decodeIfPresent([ShopItem].self, forKey: .latest)
    }

之后,图像仍然没有显示原因:

decoder.keyDecodingStrategy = .convertFromSnakeCase

我只是删除了这行代码,它开始工作。

相关问题