David Seek
David Seek

Reputation: 17132

Dispatch group functions not called - how to use dispatch group?

I have several functions to retrieve data from firebase. I want an activity indicator to spin until all the data is retrieved.

My problem is that, the functions aren't even started. To search for the mistake I've entered print statements which aren't called.

This is my code:

override func viewDidLoad() {
    super.viewDidLoad()
    loadingActInd.hidesWhenStopped = true
    self.loadingActInd.startAnimating()      

    let group = dispatch_group_create()

    dispatch_group_enter(group)
    func loadTweetComplete() {
        dispatch_group_leave(group)
    }

    dispatch_group_enter(group)
    func loadEventsComplete() {
        dispatch_group_leave(group)
    }

    dispatch_group_notify(group, dispatch_get_main_queue()) {
        self.loadingActInd.stopAnimating()
        print("deejayTweetsDictionary = \(deejayTweetsDictionary)")
        print("finished executing")
    }

}

func loadTweetComplete(completionHandler: () -> ()) {

    print("TEST")

    deejayTweetsDictionary.removeAll()

    let usersRef = firebase.child("DeejayTweets").child(passedDJ.objectId)
    usersRef.observeSingleEventOfType(.Value, withBlock: { snapshot in

        if snapshot.exists() {

            deejayTweetsDictionary.removeAll()

            let sorted = (snapshot.value!.allValues as NSArray).sortedArrayUsingDescriptors([NSSortDescriptor(key: "date",ascending: false)])

            for element in sorted {

                deejayTweetsDictionary.append(element as! NSMutableDictionary)

            }

        }

        completionHandler()
    })
}

func loadEventsComplete(completionHandler: () -> ()) {

    print("TEST")

    eventDates.removeAll()

    if passedDJ.objectId != nil {

        let userRef = firebase.child("djBookings").child(passedDJ.objectId)

        userRef.observeSingleEventOfType(.Value, withBlock: { (snapshot) in

            if snapshot.exists() {

                eventDates.removeAll()

                let item = (snapshot.value as? NSMutableDictionary)!

                let allValues = item.allValues
                for element in allValues {

                    eventDates.append(element as! NSMutableDictionary)

                }

            }

            completionHandler()
        })

    }
}

The Indicator spins forever and not even the print("TEST") statements are called. What am I doing wrong? Help is very appreciated.

Upvotes: 0

Views: 204

Answers (1)

Martin R
Martin R

Reputation: 539945

func loadTweetComplete() {
    dispatch_group_leave(group)
}

defines a (nested) function. What you want is to call the function with the given completion handler as an argument. Using the trailing closure syntax that would be

loadTweetComplete {
    dispatch_group_leave(group)
}

Upvotes: 2

Related Questions