Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

ios - Swift / How to use dispatch_group with multiple called web service?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...