mastodon-ios/Mastodon/Scene/MediaPreview/Paging/Image/MediaPreviewImageViewModel....

78 lines
2.1 KiB
Swift
Raw Normal View History

//
// MediaPreviewImageViewModel.swift
// Mastodon
//
// Created by MainasuK Cirno on 2021-4-28.
//
2021-04-30 13:28:06 +02:00
import os.log
import UIKit
import Combine
2021-04-30 13:28:06 +02:00
import AlamofireImage
class MediaPreviewImageViewModel {
// input
let item: ImagePreviewItem
2021-04-30 13:28:06 +02:00
// output
let image: CurrentValueSubject<UIImage?, Never>
let altText: String?
2021-04-28 14:10:17 +02:00
init(meta: RemoteImagePreviewMeta) {
self.item = .status(meta)
2021-04-30 13:28:06 +02:00
self.image = CurrentValueSubject(meta.thumbnail)
self.altText = meta.altText
2021-04-30 13:28:06 +02:00
let url = meta.url
ImageDownloader.default.download(URLRequest(url: url), completion: { [weak self] response in
guard let self = self else { return }
switch response.result {
case .failure(let error):
os_log(.info, log: .debug, "%{public}s[%{public}ld], %{public}s: download image %s fail: %s", ((#file as NSString).lastPathComponent), #line, #function, url.debugDescription, error.localizedDescription)
case .success(let image):
os_log(.info, log: .debug, "%{public}s[%{public}ld], %{public}s: download image %s success", ((#file as NSString).lastPathComponent), #line, #function, url.debugDescription)
self.image.value = image
}
})
}
init(meta: LocalImagePreviewMeta) {
self.item = .local(meta)
2021-04-30 13:28:06 +02:00
self.image = CurrentValueSubject(meta.image)
self.altText = nil
}
}
extension MediaPreviewImageViewModel {
enum ImagePreviewItem {
2021-04-28 14:10:17 +02:00
case status(RemoteImagePreviewMeta)
case local(LocalImagePreviewMeta)
var activityItems: [Any] {
var items: [Any] = []
switch self {
case .status(let meta):
items.append(meta.url)
case .local(let meta):
items.append(meta.image)
}
return items
}
}
2021-04-28 14:10:17 +02:00
struct RemoteImagePreviewMeta {
let url: URL
let thumbnail: UIImage?
let altText: String?
}
struct LocalImagePreviewMeta {
let image: UIImage
}
}