0

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()
    
}
burnsi
  • 6,194
  • 13
  • 17
  • 27
fdeis
  • 1
  • 1
  • *Who* does create the file? – vadian Feb 14 '23 at 16:15
  • It could be bom files or log files created with another app or a script. One of the uses would be a script that runs a workflow, I could use the app to present the user with the steps being run and completed. – fdeis Feb 14 '23 at 16:29
  • 3
    Waiting is bad and sleeping on a thread is worse. Better than `DispatchGroup` is `DispatchSource` and a file descriptor to monitor a directory. It **notifies** when a file appears (for example see https://stackoverflow.com/questions/7867991/nsfilemanager-watch-directory). – vadian Feb 14 '23 at 16:38
  • That was one of my options, but I want to WAIT until a specific file is created, then move on to the next and so on until the array is complete. – fdeis Feb 15 '23 at 18:28

0 Answers0