ios_app/Shared/Components/RemoteImageView.swift
2025-08-14 19:41:07 +03:00

59 lines
1.5 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import SwiftUI
import Combine
// 1. Класс для загрузки изображения
class ImageLoader: ObservableObject {
@Published var image: UIImage?
private var cancellable: AnyCancellable?
private let url: URL
init(url: URL) {
self.url = url
}
deinit {
cancellable?.cancel()
}
func load() {
cancellable = URLSession.shared.dataTaskPublisher(for: url)
.map { UIImage(data: $0.data) }
.replaceError(with: nil)
.receive(on: DispatchQueue.main)
.assign(to: \.image, on: self)
}
func cancel() {
cancellable?.cancel()
}
}
// 2. View для отображения удаленного изображения
struct RemoteImageView: View {
@StateObject private var loader: ImageLoader
private let placeholder: Image
init(url: URL, placeholder: Image = Image("placeholderPhoto")) {
_loader = StateObject(wrappedValue: ImageLoader(url: url))
self.placeholder = placeholder
}
var body: some View {
content
.onAppear(perform: loader.load)
.onDisappear(perform: loader.cancel)
}
private var content: some View {
Group {
if let image = loader.image {
Image(uiImage: image)
.resizable()
} else {
placeholder
.resizable()
}
}
}
}