When a user creates a new group in my application, I have to click on the prompts to the database, as well as other information. I started using Dispatch Groups to track when all the information was sent successfully, so I can decline the view.
I am trying to use a send group for invitations and another send group for all the data. Here is what I have:
// Push new data to db func createGroup(onSccess completion:@escaping () -> Void) { let inviteDispatchGroup = DispatchGroup() let dataDispatchGroup = DispatchGroup() let uid = FIRAuth.auth()?.currentUser?.uid let name = String(uid!) + "_" + nameTextField.text! // push invites dataDispatchGroup.enter() for invite in invites { inviteDispatchGroup.enter() let ref = FIRDatabase.database().reference().child("users").child(invite.id).child("invites") ref.updateChildValues([name: nameTextField.text!]) { (error, ref) -> Void in inviteDispatchGroup.leave() } } inviteDispatchGroup.notify(queue: DispatchQueue.main, execute: { dataDispatchGroup.leave() }) // store picture dataDispatchGroup.enter() let storageRef = FIRStorage.storage().reference().child("profile_images").child("\(name).png") if let uploadData = UIImagePNGRepresentation(profImage.resizeImage(targetSize: CGSize(width: 500, height: Int(500*(profImage.size.height/profImage.size.width))))) { storageRef.put(uploadData, metadata: nil, completion: { (metadata, error) in dataDispatchGroup.leave() }) } // store pet info dataDispatchGroup.enter() let petRef = FIRDatabase.database().reference().child("pets").child(name) petRef.setValue(["mod":uid!, "name":nameTextField.text!, "members":[uid!]]) { (error, ref) -> Void in dataDispatchGroup.leave() } // store user info dataDispatchGroup.enter() let userRef = FIRDatabase.database().reference().child("users").child(uid!).child("pets") userRef.updateChildValues([name: true]) { (error, ref) -> Void in dataDispatchGroup.leave() } dataDispatchGroup.notify(queue: DispatchQueue.main, execute: { completion() }) }
As you can see, upon completion of invitesDipatchGroup corresponding invitesDipatchGroup corresponds.
I am new to Dispatch groups and want to hear if this is the right approach to this task.
source share