Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make one code run only after the other is done in Swift

I am new to async and sync mechanism. In my code I have to perform one code line only after the other is done. It looks something like this:

    func something(){

    let workerQueue = DispatchQueue.global(qos: .userInitiated)
            workerQueue.async{
         let info = getInfoFromTheWeb()//I need the info value in order to perform the next line
         saveToDB(info: info)

      DispatchQueue.main.async {
       //update a label text in the ui after getting and saving that info
      }

    }
}

Your professional thoughts please..

like image 792
Shira Avatar asked Oct 16 '25 14:10

Shira


1 Answers

Your should DispatchGroup. By using DispatchGroup one function/line of code will wait until the other function completes execution.

For example

let myGroup = DispatchGroup()
   myGroup.enter()
   let info = getInfoFromTheWeb()

When you get info from simple call

myGroup.leave()

When your call leave() function following code will be execute

myGroup.notify(queue: DispatchQueue.main) {

            saveToDB(info: info)
           /// Update UI elements
        }
like image 123
Usman Javed Avatar answered Oct 19 '25 04:10

Usman Javed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!