SwiftUI ProgressView with an asynchronous method

Viewed 495

I'm trying to create a progress bar update with an asynchronous method.

I'm using the code:

struct ContentView: View {

    @ObservedObject var demo:teste

     var body: some View {

        VStack{

            ProgressView("Loading....", value: demo.i, total: demo.x)

            Button("Start Loading") {

                demo.demo()

            }

        }

    }

}

class teste:ObservableObject{

    @Published var i:Float = 0

    @Published var x:Float = 100

  

    func demo(){

        DispatchQueue.global(qos: .default).async {

            DispatchQueue.main.sync {

                for _ in 0 ... 20{

                    self.i += Float(5.0)

                    sleep(5)

                }

            }

        }

    }

}

My goal and that the porgressView will be filled according to the value of (i). The value inside the class (i) is updated, but the view isn't. 

So how i can update the progress view with the value of i? 

1 Answers

Try this one

    func demo(){
        DispatchQueue.global(qos: .background).async {
            for _ in 0 ... 20{
                sleep(5)         // wait in background
                DispatchQueue.main.sync {
                    self.i += Float(5.0)    // update in main
                }
            }
        }
    }
Related