45 lines
1.8 KiB
Swift
45 lines
1.8 KiB
Swift
import Foundation
|
|
|
|
/// 推进空镜库本地下载演示,不发起网络请求,也不写入文件或系统相册。
|
|
@MainActor
|
|
final class ScenicMaterialDemoDownloadDriver {
|
|
private var task: Task<Void, Never>?
|
|
private var activeBatchID: UUID?
|
|
|
|
/// 只推进当前批次的未完成项,旧批次回执由 ViewModel 再次校验。
|
|
func start(viewModel: ScenicMaterialsViewModel, onProgress: @escaping () -> Void) {
|
|
guard viewModel.phase == .downloading, let batchID = viewModel.batchID else { return }
|
|
guard activeBatchID != batchID || task == nil else { return }
|
|
stop()
|
|
activeBatchID = batchID
|
|
let itemIDs = viewModel.pendingIDs
|
|
task = Task { @MainActor [weak self, weak viewModel] in
|
|
guard let self, let viewModel else { return }
|
|
defer {
|
|
if self.activeBatchID == batchID {
|
|
self.task = nil
|
|
self.activeBatchID = nil
|
|
}
|
|
}
|
|
for id in itemIDs where !viewModel.completedIDs.contains(id) {
|
|
for progress in [0.2, 0.45, 0.7, 0.95] {
|
|
do { try await Task.sleep(nanoseconds: 200_000_000) } catch { return }
|
|
guard !Task.isCancelled, self.activeBatchID == batchID,
|
|
viewModel.batchID == batchID, viewModel.phase == .downloading else { return }
|
|
viewModel.receive(.progress(progress), clipID: id, batchID: batchID)
|
|
onProgress()
|
|
}
|
|
viewModel.receive(.completed, clipID: id, batchID: batchID)
|
|
onProgress()
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 停止演示计时;调用方另行暂停或取消批次,避免把取消计时视为下载成功。
|
|
func stop() {
|
|
task?.cancel()
|
|
task = nil
|
|
activeBatchID = nil
|
|
}
|
|
}
|