首页 > 解决方案 > 如何在 swiftui 中显示来自网络的图像?

问题描述

我最近一直在使用 swiftUI 构建一个应用程序,该应用程序具有显示从网络下载的图像的功能。我试图让它工作,但我现在遇到了麻烦。我想也许 ImageFetcher.swift 有问题?谁能帮我吗?这是我的代码:

ImageFetcher.swift :

import Foundation
import Combine
import SwiftUI

class ImageFetcher: ObservableObject {
var didChange = PassthroughSubject<Data, Never>()

var data: Data = Data() {
    didSet {
        didChange.send(data)
    }
}

init(url: String) {
    guard let imageUrl = URL(string: url) else {
        return
    }

    URLSession.shared.dataTask(with: imageUrl) { (data, _, _) in
        guard let data = data else { return }
        DispatchQueue.main.async { [weak self] in
            self?.data = data
        }

    }.resume()
}
}

LoadableImageView.swift :

import SwiftUI

struct LoadableImageView: View {
@ObservedObject var imageFetcher: ImageFetcher

var stateContent: AnyView {
    if let image = UIImage(data: imageFetcher.data) {
        return AnyView(
            Image(uiImage: image).resizable()
        )
    } else {
        return AnyView(
            ActivityIndicator(style: .medium)
        )
    }
}

init(with urlString: String) {
    imageFetcher = ImageFetcher(url: urlString)
}

var body: some View {
    HStack {
        stateContent
    }
}
}

struct LoadableImageView_Previews : PreviewProvider {
static var previews: some View {
    LoadableImageView(with: "https://is2-ssl.mzstatic.com/image/thumb/Music113/v4/3d/6d/d0/3d6dd00b-b480-740f-bc6e-e2ca78ff918e/190296882920.jpg/200x200bb.png")
}
}

ListCellView.swift :

import SwiftUI
import Foundation
import AlamofireImage
import Alamofire
import Combine


struct ListCellView: View {


@State var dataSource = DataSource()
var viewModel: RestrauntListViewModel
var imageLoader = ImageLoader()

var body: some View {
    HStack {

        LoadableImageView(with: viewModel.imageURL.absoluteString)

        Spacer()
        VStack(alignment: .center, spacing: 1.0) {
            Text(viewModel.name)

            Image(dataSource.configureRatings(rating: viewModel.rating))
            Text("\(viewModel.formattedDistance) miles")
        }
        .padding(.all)
        Spacer()
    }
}
}
struct ListCellView_Previews: PreviewProvider {

static var previews: some View {
    ListCellView(viewModel: RestrauntListViewModel(name: "in 3nout", imageURL: URL(string: "https://s3-media2.fl.yelpcdn.com/bphoto/FNYCY1myO6qlqXLTpGPyIA/o.jpg")!, distance: 4.94578764532, id: "34526434", rating: 4))
}
}

标签: swiftimagedownloadswiftuicombine

解决方案


推荐阅读