在网址列表中显示图像

时间:2019-11-06 00:52:39

标签: swiftui

我有一个从JSON API填充的列表。

ForEach(booksVM.books.sorted { $0.popularidad > $1.popularidad}) { book in
    HStack {
        Image(URL: book.imagen)
        Text(book.nombre)
        Spacer()
    }
    Text(book.autor)
    Spacer()
}

第三行是错误的,但这是我要实现的目标。

现在,book.imagen是JSON所有图像URL的Decodable变量。我该怎么办?

JSON以防万一:

[
{
    "id": 1,
    "nombre": "The design of every day things",
    "autor": "Don Norman",
    "disponibilidad": true,
    "popularidad": 70,
    "imagen": "https://images-na.ssl-images-amazon.com/images/I/410RTQezHYL._SX326_BO1,204,203,200_.jpg"
},
{
    "id": 2,
    "nombre": "100 años de soledad",
    "autor": "Garcia Marquez",
    "disponibilidad": false,
    "popularidad": 43,
    "imagen": "https://images-na.ssl-images-amazon.com/images/I/51egIZUl88L._SX336_BO1,204,203,200_.jpg"
}
]

和结构:

struct Book: Identifiable, Decodable {
    let id: Int
    let nombre: String
    let autor: String
    let disponibilidad: Bool
    let popularidad: Int
    let imagen: String
}

1 个答案:

答案 0 :(得分:0)

Here我找到了一个决定并为您修改了。这个想法是用 ImageLoader 类创建 ImageView

struct ImageView: View {
    @ObservedObject var imageLoader:ImageLoader
    @State var image:UIImage = UIImage()

    func imageFromData(_ data:Data) -> UIImage {
        UIImage(data: data) ?? UIImage()
    }

    init(withURL url:String) {
        imageLoader = ImageLoader(urlString:url)
    }

    var body: some View {
        VStack {

            Image(uiImage: imageLoader.data != nil ? UIImage(data:imageLoader.data!)! : UIImage())
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width:100, height:100)
        }
    }

}

class ImageLoader: ObservableObject {
    @Published var dataIsValid = false
    var data:Data?

    init(urlString:String) {
        guard let url = URL(string: urlString) else { return }
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data else { return }
            DispatchQueue.main.async {
                self.dataIsValid = true
                self.data = data
            }
        }
        task.resume()
    }
}

现在您可以将其用于列表:

struct ListView: View {
    let urls = ["https://images-na.ssl-images-amazon.com/images/I/410RTQezHYL._SX326_BO1,204,203,200_.jpg", "https://images-na.ssl-images-amazon.com/images/I/51egIZUl88L._SX336_BO1,204,203,200_.jpg"]

    var body: some View {
        List {
            ForEach(urls, id: \.self) { url in
                ImageView(withURL: url)
            }
        }
    }
}

这是预览结果: enter image description here