Created
April 8, 2017 04:11
-
-
Save keith-kurak/faebf0f8943c66f091eb56ec88fbf3b1 to your computer and use it in GitHub Desktop.
Tags then posts with dispatch groups
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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