I would like a for in loop to send off a bunch of network requests to firebase, then pass the data to a new view controller once the the method finishes executing. Here is my code:
var datesArray = [String: AnyObject]()
for key in locationsArray {
let ref = Firebase(url: "http://myfirebase.com/" + "\(key.0)")
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
datesArray["\(key.0)"] = snapshot.value
})
}
//Segue to new view controller here, and pass datesArray once it is complete
I have a couple concerns. First, how do I wait until the for loop is finished and all the network requests are complete? I can't modify the observeSingleEventOfType function, it is part of the firebase SDK. Also, will I create some sort of race condition by trying to access the datesArray from different iterations of the for loop (hope that makes sense)? I've been reading about GCD and NSOperation but I'm a bit lost as this is the first app I've built.
Note: Locations array is an array containing the keys I need to access in firebase. Also, it's important that the network requests are fired off asynchronously. I just want to wait until ALL the asynchronous requests complete before I pass the datesArray to the next view controller.
Swift 3: You could also use semaphores on this way. It results very helpful, besides you can keep exact track on when and what processes are completed. This has been extracted from my code:
You will need to use semaphores for this purpose.
You can use dispatch groups to fire an asynchronous callback when all your requests finish.
Here's an example in Swift 4.1 (works in Swift 3 too) using dispatch groups to execute a callback asynchronously when multiple networking requests have all finished.
Output
For those using the older Swift 2.3, here's an example using its syntax:
Details
Xcode 9.2, Swift 4
Solution
Usage
Full sample
Results
Sample 1
Sample 2
Xcode 8.3.1 - Swift 3
This is the accepted answer of paulvs, converted to Swift 3:
Swift 3 or 4
If you don't care about orders, use @paulvs's answer, it works perfectly.
else just in case if anyone wants to get the result in order instead of fire them concurrently, here is the code.