Home > AI > IOS > Combine >

dataTaskPublisher

Example 1: download an image

Demo.swift

import Foundation
import Combine
import UIKit


class Demo: ObservableObject {
    @Published var image: UIImage?
    var subscription: AnyCancellable?
    static let placeholder = UIImage(systemName: "pencil")!



    func load() {
        let urlString = "https://www.jobyme88.com/wp-content/uploads/2020/11/50d0-kj-classroom-0.jpg"
        let url = URL(string: urlString)!
        subscription = URLSession.shared.dataTaskPublisher(for: url)
            .map { UIImage(data: $0.data) }
            .replaceError(with: nil)
            .receive(on: DispatchQueue.main)
            .assign(to: \.image, on: self)
    }
}

ContentView.swift

import SwiftUI

struct ContentView: View {
    @ObservedObject var demo: Demo
    
    init() {
        demo = Demo()
        demo.load()
    }
    
    var body: some View {
        Image(uiImage: demo.image ?? Demo.placeholder)
            .resizable()
            .aspectRatio(contentMode: .fit)
    }
}

Leave a Reply