I am using dispatch_group
to call Firebase requesting functions and get notified once the request is complete to be able to work with the result then. In this scenario I've just put a print statement.
func loadStuff() {
dispatch_group_enter(group)
myFirebaseFunction() {
dispatch_group_leave(group)
}
dispatch_group_notify(group, dispatch_get_main_queue()) {
print("done")
}
}
func myFirebaseFunction(completionHandler: () -> ()) {
let usersRef = firebase.child("likes")
usersRef.observeEventType(.Value, withBlock: { snapshot in
if snapshot.exists() {
let sorted = (snapshot.value!.allValues as NSArray).sortedArrayUsingDescriptors([NSSortDescriptor(key: "date",ascending: false)])
for item in sorted {
dict.append(item as! NSDictionary)
}
}
completionHandler()
})
}
This code is working fine. The problem is that, during runtime, data will be added into the Firebase Database. That is why I have to use observeEventType
instead of observeSingleEventOfType
.
This means there is an observer during runtime and in case data has been added to the database, the block within myFirebaseFunction
will be called again.
Once this happens, the app crashes because dispatch_group_leave(group)
has been called without dispatch_group_enter(group)
. As long as I got this right.
dispatch_group_enter(group)
myFirebaseFunction() {
dispatch_group_leave(group) // crash here
}
If I change it to observeSingleEventOfType
, no crash occurs, but new added Data to Firebase will not be observed.
What's the best practice to use dispatch_group
with multiple run Web Services? Or what do I have to do to fix my issue? Help is very appreciated.
PS Currently I'm using Swift 2.3, but an upgrade to Swift 3 is planned, so it would be very awesome to receive an answer capable for both.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…