0

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.

AL.
  • 36,815
  • 10
  • 142
  • 281
yonasstephen
  • 2,645
  • 4
  • 23
  • 48
  • 1
    What about http://stackoverflow.com/questions/27177268/how-to-run-synchronically-two-functions-with-async-operations-on-ios-using-swift – rmaddy Sep 13 '16 at 16:00
  • @rmaddy hmm that might work.. but I'd prefer a cleaner solution without having to create an array of `NSOperationQueue` thanks btw! I will give it a shot later – yonasstephen Sep 13 '16 at 16:08

1 Answers1

2

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.

tonik12
  • 613
  • 1
  • 7
  • 25
  • wew that's quite a fundamental and clean solution; why didn't I think of that... well I guess for the sake of learning, let's see if other people have other better suggestions. if not, I will try this and vote as answer – yonasstephen Sep 13 '16 at 16:13
  • @yonasstephen did it work for you? or did you find another (maybe better) solution for it? – tonik12 Sep 14 '16 at 10:00