Skip to content

Instantly share code, notes, and snippets.

@peterfoxflick
Last active November 6, 2020 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterfoxflick/ef49da3574202786615fa8f4db226809 to your computer and use it in GitHub Desktop.
Save peterfoxflick/ef49da3574202786615fa8f4db226809 to your computer and use it in GitHub Desktop.
Progress view updated by threads in SwiftUI
import SwiftUI
struct ContentView: View {
@State var total = 0
@State var progress = 0
@State private var workItem: DispatchWorkItem?
var body: some View {
if(self.total = 0){
VStack {
//Some view to select items from the array here
//Button to begin the process
Button(action: {
self.doStuff()
}) {
Image(systemName: "square.and.arrow.down")
}
}.padding()
} else {
VStack{
//Loading bar
ProgressView("Saving...", value: Double(self.progress), total: Double(self.total))
//Add a cancel button
Button(action: {
self.workItem?.cancel()
self.total = 0
self.progress = 0
}) {
Image(systemName: "xmark.octagon")
}
}.padding()
}
}
func doStuff() {
let items = [] //For my case I was looping through an array
self.total = items.count //but you can replace this with the total number of items that need to be processed
self.progress = 0
self.workItem = DispatchWorkItem {
for item in items {
//Do your complicated work here
//Update progress using the main thread each loop iteration
DispatchQueue.main.async { self.progress += 1 }
}
//Reset variables on the main thread once finished
DispatchQueue.main.async{
self.progress = 0
self.total = 0
}
}
//Start the work item
if(workItem != nil) {
DispatchQueue.global().async(execute: workItem!)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment