Skip to content

Instantly share code, notes, and snippets.

@keith-kurak
Created April 8, 2017 04:11
Show Gist options
  • Save keith-kurak/faebf0f8943c66f091eb56ec88fbf3b1 to your computer and use it in GitHub Desktop.
Save keith-kurak/faebf0f8943c66f091eb56ec88fbf3b1 to your computer and use it in GitHub Desktop.
Tags then posts with dispatch groups
func posts(forTag tagKey: String, completionBlock: (([Post]) -> ()) {
let userId = FIRAuth.auth().currentUser?.uid
let ref = FIRDatabase.database().reference()
let dispatchGroup = DispatchGroup()
var posts = [Post]() //I can put all the posts here as I retrieve them
ref.child("users").child(userId!).child("tags").child(tagKey).observeSingleEvent(of: .value, with: {(tagSnapshot) in
let tag = Tag(fromSnapshot: tagSnapshot)
dispatchGroup.enter() //starting an async op
for postKey in tags.postKeys {
ref.child("users").child(userId!).child("posts").child(postKey).observeSingleEvent(of: .value, with: {(postSnapshot)
//Seems that we need to get back to a single thread, since our array will not be thread-safe
DispatchQueue.main.async {
posts.append(Post(fromSnapshot: postSnapshot))
dispatchGroup.leave() //ending an async op
}
})
}
//wait for all the "entered" aysnc ops to "leave", then run the completion blocks
dispatchGroup.notify(queue: DispatchQueue.main, execute: {
completionBlock(posts)
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment