Search code examples
iosswiftswift3grand-central-dispatchios-multithreading

How to ensure calls are done serially in swift3 app using GCD


I need this block of code to run in order:

UIApplication.shared.beginIgnoringInteractionEvents()
loadDataTask.resume()
UIApplication.shared.endIgnoringInteractionEvents()

It's being run inside of DispatchQueue.main.async() (every network call is that's why I'm trying to temporarily block user input). I am still learning swift and struggling a little with the GCD concept. Any recommendations would be very much appreciated.


Solution

  • Just put the endIgnoringInteractionEvents call inside the completion handler of loadDataTask.

    UIApplication.shared.beginIgnoringInteractionEvents()
    let loadDataTask = session.dataTask(with: request) { data, response, error in
        ...
    
        DispatchQueue.main.async {
            // do all UI and model updates here
    
            UIApplication.shared.endIgnoringInteractionEvents()
        }
    }
    loadDataTask.resume()