How to scan a folder asynchronously in SwiftUI 6?

3 days ago 3
ARTICLE AD BOX

I can do it with Swift 5, but I do not know how to fix the compilation error with Swift 6. I browsed the net for weeks, made tests and tests, but no solution. Could you help please? I wrote a small app to count the files in My Documents. Here is the code.

Regards.

import SwiftUI import Combine @MainActor final class FileScannerViewModel: ObservableObject { @Published var scannedCount: Int = 0 @Published var isScanning: Bool = false private var scanTask: Task<Void, Never>? func startScan() { guard !isScanning else { return } scannedCount = 0 isScanning = true scanTask = Task { let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! await scanDirectory(at: documentsURL) if !Task.isCancelled { await MainActor.run { self.isScanning = false } } } } func cancelScan() { scanTask?.cancel() scanTask = nil isScanning = false } private func scanDirectory(at url: URL) async { let fileManager = FileManager.default guard let enumerator = fileManager.enumerator(at: url, includingPropertiesForKeys: nil) else { return } for case let fileURL as URL in enumerator { if Task.isCancelled { return } await MainActor.run { self.scannedCount += 1 } await Task.yield() } } } struct ContentView: View { @StateObject private var viewModel = FileScannerViewModel() var body: some View { VStack(spacing: 20) { Text("Fichiers scannés : \(viewModel.scannedCount)") if viewModel.isScanning { ProgressView() .progressViewStyle(.circular) } HStack { Button("Lancer le scan") { viewModel.startScan() } .disabled(viewModel.isScanning) Button("Annuler") { viewModel.cancelScan() } .disabled(!viewModel.isScanning) } } } }
Read Entire Article