Skip to content

Instantly share code, notes, and snippets.

@keith-kurak
Created April 8, 2017 03:56
Show Gist options
  • Save keith-kurak/6a105ed9cc288a2efb3ad973a3895336 to your computer and use it in GitHub Desktop.
Save keith-kurak/6a105ed9cc288a2efb3ad973a3895336 to your computer and use it in GitHub Desktop.
Query posts for tags
// Assumption: you have nice business objects for Posts and Tags that you build from Firebase snapshots
func posts(forTag tagKey: String, completionBlock: (([Post]) -> ()) {
let userId = FIRAuth.auth().currentUser?.uid
let ref = FIRDatabase.database().reference()
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)
for postKey in tags.postKeys {
ref.child("users").child(userId!).child("posts").child(postKey).observeSingleEvent(of: .value, with: {(postSnapshot)
//This is async. CRAP HOW DO I GET IT TO WAIT FOR EACH OF THESE TO BE DONE BEFORE CALLING THE COMPLETION BLOCK?!
})
}
completionBlock(posts) //This will be empty because it will run before any of the post queries run. If I stick it in the inner completionBlock, the consumer will only get one Post.
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment