0

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()
//        }
//    }
}



Daniel DE
  • 85
  • 1
  • 8
  • You have a lot of irrelevant code, such as your foreground colors, import statements, and frames. Try editing these out of the question... it'll make it a lot easier to get answers! – Stoic Nov 25 '22 at 19:41

0 Answers0