yonasstephen
yonasstephen

Reputation: 2725

Swift iOS: How to force a loop with async code to run synchronously?

So I have this code below:

func handleSendPost() {
    let postRef = Global.FIRDB!.child("posts").childByAutoId()

    for p in postComponents {
        var values: [String : Any] = ["type": p.type!.rawValue, "text": p.text]

        let childRef = reference.childByAutoId()
        childRef.updateChildValues(values, withCompletionBlock: {
            (err, ref) in

            if err != nil {
                print(err)
                return
            }

            // object successfully saved
        })
    }
}

It's basically an iOS app for blogging. When someone creates a post, it's broken down into components that could be text or an image. After they're done editing, it will be stored on Firebase by calling the updateChildValues async function. The problem is that I want to maintain the order of postComponents. If I ran the code above, the order could mess up because it depends on how fast the updateChildValues runs.

I've already tried using DispatchSemaphore (iOS 10) to no avail.

Upvotes: 0

Views: 1703

Answers (1)

tonik12
tonik12

Reputation: 613

There could be other way but I guess you could forget the loop and use recursion instead. The flow would be like:

  1. Store the elements in an array.
  2. Call function that sends first element if there is at least one element in the array.
  3. In the completion block, remove the first element of the array and repeat step 2.

This will send all the elements in order and stop when no more elements.

Upvotes: 2

Related Questions