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.

2
  • 1
    What about stackoverflow.com/questions/27177268/… Commented Sep 13, 2016 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 Commented Sep 13, 2016 at 16:08

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 did it work for you? or did you find another (maybe better) solution for it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.