Hello! I want to display progress during my operation. I'm new to swift and swiftui. Please help... Here is the model with one async method:
class CountriesViewModel : ObservableObject {
@Published var countries: [String] = [String]()
@Published var isFetching: Bool = false
@MainActor
func fetch() async {
countries.removeAll()
isFetching = true
countries.append("Country 1")
Thread.sleep(forTimeInterval: 1)
countries.append("Country 2")
Thread.sleep(forTimeInterval: 1)
countries.append("Country 3")
Thread.sleep(forTimeInterval: 1)
isFetching = false
}
}
and the ContentView:
struct ContentView: View {
@StateObject var countriesVM = CountriesViewModel()
var body: some View {
ZStack {
if (countriesVM.isFetching) {
ProgressView("Fetching...")
}
else {
List {
ForEach(countriesVM.countries, id: \.self) { country in
Text(country)
}
}
.task {
await countriesVM.fetch()
}
.refreshable {
Task {
await countriesVM.fetch()
}
}
}
}
}
}
The progress is not displayed. What am I doing wrong?