Using DispatchGroup within multiple for loop - Swift & Firebase

275 views Asked by At

I'm having an issue with getting dispatchgroup functions to work when combined with multiple for loops. In my code below, my first dispatch pulls in the coauthorId field for each of the coauthorID under my userId.

I'm getting an error when the code reaches the first dispatchgroup.leave() function so I'm not sure if it has something to do with where the dispatchgroup functions are placed.

Datebase structure:

posts
  --ABC //my userId
    --XXX //coauthorId
      --coauthorId: XXX
    --ZZZ //coauthorId
      --coauthorId: ZZZ
  --YYY //coauthorId
      --coauthorId: YYY

Code:

    var ListA = [String]()
    var ListB = [String]()

    func fetchPosts() {

    let dispatchGroup = DispatchGroup()

    let currentUser = Auth.auth().currentUser!

    dispatchGroup.enter() 
    Database.database().reference().child("posts").child(currentUser.uid).observeSingleEvent(of: .value, with: { (snapshot : DataSnapshot) in

        // Iterate through all the children:

        for child in snapshot.children.allObjects as! [DataSnapshot] {

            let value = child.value as? NSDictionary

            let coauthorId = value?["coauthorId"] as? String ?? ""
         Database.database().reference().child("posts").child(coauthorId).observeSingleEvent(of: .value, with: { (snapshot : DataSnapshot) in

                // Iterate through all the children:

                for child1 in snapshot.children.allObjects as! [DataSnapshot] {

                    let value1 = child1.value as? NSDictionary

                    let coauthorId1 = value1?["coauthorId"] as? String ?? ""

                    self.ListA.append(coauthorId1)

                    dispatchGroup.leave() //this is where I get an error

                }
            })

        }

    })

            dispatchGroup.enter()

    //fetches the Id of my posts

    Database.database().reference().child("posts").child(currentUser.uid).observeSingleEvent(of: .value, with: { (snapshot : DataSnapshot) in

        // Iterate through all the children:

        for child in snapshot.children.allObjects as! [DataSnapshot] {
            // Add the user ID to the array:

            let value = child.value as? NSDictionary

            let mycoauthorId = value?["coauthorId"] as? String ?? ""

            self.ListB.append(mycoauthorId)

        }
        dispatchGroup.leave()
    })

    // Notify the dispatch group:

    dispatchGroup.notify(queue: DispatchQueue.main, execute: {

        // Now that both completion blocks (from your two observers) ran, combine both arrays

        let combinedArray = self.ListA + self.ListB
        print(combinedArray)

        })
0

There are 0 answers