Home > AI > IOS > SwiftUI >

Download an image with a placeholder

PlaceholderImageView.swift

//
//  PlaceholderImageView.swift
//  aa
//
//  Created by dph on 2020/12/6.
//

import SwiftUI

struct PlaceholderImageView: View {
    @ObservedObject var imageModel: PlaceholderImageViewModel
    static private var placeholder: UIImage = UIImage(systemName: "pencil")!
    
    init(urlString: String) {
        imageModel = PlaceholderImageViewModel(urlString: urlString)
    }
    
    var body: some View {
        Image(uiImage: imageModel.image ?? PlaceholderImageView.placeholder)
            .resizable()
            .scaledToFit()
    }
}

struct PlaceholderImageView_Previews: PreviewProvider {
    static var previews: some View {
        PlaceholderImageView(urlString: "https://www.jobyme88.com/wp-content/uploads/2020/11/50d0-kj-classroom-0.jpg")
    }
}

PlaceholderImageViewModel.swift

//
//  PlaceholderImageViewModel.swift
//  aa
//
//  Created by dph on 2020/12/6.
//

import Foundation
import SwiftUI



class PlaceholderImageViewModel: ObservableObject {
    @Published var image: UIImage?
    var urlString: String?
    
    
    init (urlString: String){
        self.urlString = urlString
        loadImage()
    }
    
    func loadImage() {
        guard self.urlString != nil else { return }
        let url = URL(string: self.urlString!)!
        let task = URLSession.shared.dataTask(with: url, completionHandler: imageResponse(data:response:error:))
        task.resume()
    }
    
    func imageResponse(data: Data?, response: URLResponse?, error: Error?){
        guard error == nil else {
            print("Error: \(error!)")
            return
        }
        guard let data = data else {
            print("No data found")
            return
        }
        guard let loadImage = UIImage(data: data) else {
            print("Not supported data")
            return
        }
        self.image = loadImage
    }
}

Leave a Reply