This is a simple sample of MVVM architecture which realize loading an image with a placeholder.
ImageViewModel.swift
import Foundation
import SwiftUI
import Combine
class ImageViewModel: ObservableObject {
@Published var uiImage: UIImage?
private var str: String = "https://img.ivsky.com/img/tupian/pre/202005/03/banma-001.jpg"
private var cancellable: AnyCancellable?
init() {
cancellable = URLSession.shared.dataTaskPublisher(for: URL(string: str)!)
.map { UIImage(data: $0.data) }
.receive(on: DispatchQueue.main)
.replaceError(with: nil)
.assign(to: \.uiImage, on: self)
}
}
TestView.swift
import SwiftUI
struct TestView<Placeholder: View>: View {
@ObservedObject private var imageViewModel: ImageViewModel
var placeholder: Placeholder
init(placeholder: Placeholder) {
self.placeholder = placeholder
imageViewModel = ImageViewModel()
}
var body: some View {
if let uiImage = imageViewModel.uiImage {
Image(uiImage: uiImage)
.resizable()
.frame(width: 100, height: 100, alignment: .center)
}
// Image(uiImage: uiImage)
else {placeholder}
}
}