Last active
November 6, 2020 03:10
-
-
Save peterfoxflick/ef49da3574202786615fa8f4db226809 to your computer and use it in GitHub Desktop.
Progress view updated by threads in SwiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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