One approach to terminating an asynchronous function signal is to use a termination handler. You have already used completion handlers in the Firebase API, and there are many APIs in the system framework, so I wonβt explain this further.
Given this approach, wrap your code in a function, say updateContacts , using a completion handler. Typically, an asynchronous function returns a calculated value or an error. In some cases, it simply succeeds or fails - without returning a value. You express this in the signature of the completion handler. Your updateContacts function may not calculate the value, but in any case, it may fail or succeed. Then you can use an optional error: if it is nil , the task succeeded, otherwise it contains an error.
When your main task is completed, call the completion handler with the result.
Note. . You must make sure that the completion handler will eventually be called!
func updateContacts(completion: (ErrorType?)-> ()) { friendsURL.observeSingleEventOfType(.Value, withBlock: { snapshot in ... ... ... usersURL.observeSingleEventOfType(.Value, withBlock: { snapshot in ... let error = // nil or an error completion(error) return } completion(nil) } }
Now that you have an array of asynchronous subtasks that will be called in parallel, and you want to pass the completion of updateContacts when all the subtasks are complete, you can use the send groups:
let group = dispatch_group_create() var error: ErrorType? contactNumbers.forEach { number in dispatch_group_enter(group) queryAsync(number) { (result, error) in if let error = error {
source share