view raw
Paco Paco - 9 months ago 37
Swift Question

How do I use dispatch_sync in swift?

this is my first time using stack overflow. I'm trying to get my program to wait for a query task to complete before moving on but I never get it to behave correctly. I put in print statements for debugging. The second and third print always comes before the first print. I think I don't really understand dispatch_sync very well. Any help would be greatly appreciated!

let concurrentQueue = dispatch_queue_create(
"com.x.TinderClone.queue", DISPATCH_QUEUE_CONCURRENT)

dispatch_sync(concurrentQueue) {
usersRef.queryOrderedByChild("gender").queryEqualToValue(userInterestedIn).observeSingleEventOfType(.Value, withBlock: {snapshot in
for child in snapshot.children {
let uid = child.key!!
let gender = child.value!!["gender"] as! String
let id = child.value!!["id"] as! String
let interestedInWomen = child.value!!["interestedInWomen"] as! Bool
let name = child.value!!["name"] as! String

let potentialMatch = User(uid: uid, gender: gender, id: id, interestedInWomen: interestedInWomen, name: name)
listOfPotentialMatches.append(potentialMatch) //add the user struct to the array

print("First") // First print

// ...
}) { (error) in

print("Second") // Second Print

print("Third") //Third print


As you've discovered, dispatch_sync isn't really helping you here. The problem is that the block you provide toobserveSingleEventOfType is passed along as an argument—not executed synchronously—and will be executed whenever Firebase deems appropriate (presumably when the event occurs).

The easiest way to make "Second" and and "Third" print after "First" would be to put them inside the block, or to put them in a function that you call at the end of the block.