I'm developing an app that needs to wait for files to be created in the disk in order to continue.
After obtaining the array of paths from the json file, I need the app to:
- Show a progress bar
- Wait for each file to be created in order
- Update the progress bar after each file is created
The problem is that when I use a .sync queue, the UI never shows and is waiting for all the files to be created, and if I use a .async queue, the UI shows and the for loop runs all the queues concurrently
do {
let jsonData = try Data(contentsOf: jsonFilePathURL)
let jsonDecoder = JSONDecoder()
let steps = try jsonDecoder.decode(Response.self, from: jsonData)
let totalStepsCount = steps.steps.count
initializeProgressBar(stepsCount:totalStepsCount)
// Run a loop for each file to watch
for step in steps.steps {
waitForFileToBeCreated(path: step.Path)
}
I use this to wait for each file to be created.
func waitForFileToBeCreated(path:String) {
let group = DispatchGroup()
group.enter()
DispatchQueue.global(qos: .default).async {
while !FileManager.default.fileExists(atPath: path) {
// Wait for the file to be created
Thread.sleep(forTimeInterval: 0.1)
}
group.leave()
}
group.wait()
}