I currently have a function that takes a while to calculate, so I want to communicate the status to the user while it runs.
I have looked around and the closest solution is this one (ProgressView updating on multiple steps of computation) but when I implement the recommended solution it still does not work.
I have also tried different iterations of using ObservedObject / StateObject but it still does not yield the desired results.
The one thing I have tried and it works but it yields other errors is using DispatchQueue.global() instead of DispatchQueue.main.
What am I doing wrong? how can I get the progress bar to update while the function is running?
(Below is the complete sample code)
import SwiftUI
struct ContentView: View {
@StateObject var progressStatus = ProgressStatus()
var body: some View {
VStack {
if progressStatus.inProgress {
VStack {
ZStack(alignment: .leading) {
RoundedRectangle(cornerRadius: 20)
.foregroundColor(.gray)
.frame(width: 300, height: 20)
RoundedRectangle(cornerRadius: 20)
.foregroundColor(.blue)
.frame(width: 300*progressStatus.progressCount/1000000, height: 20)
}
ProgressView(value: progressStatus.progressCount/1000000)
}
}
Button("Run Loop") {
runLoop()
}
}
}
func runLoop() {
var i: Int = 1
var j: Int = 1
DispatchQueue.main.async {
progressStatus.progressCount = CGFloat(1)
progressStatus.inProgress = true
while (i < 1000) {
j = 1
while (j < 1000) {
j = j + 1
progressStatus.progressCount = progressStatus.progressCount + CGFloat(1)
print(progressStatus.progressCount)
}
i = i + 1
}
//progressStatus.progressCount = CGFloat(100)
}
return
}
}
class ProgressStatus: ObservableObject {
@Published var inProgress: Bool = true
@Published var progressCount: CGFloat = 0
// {
// willSet {
// objectWillChange.send()
// }
// }
}