使用dispatch_group_async从嵌套异步调用获取通知

时间:2015-10-04 16:02:03

标签: ios facebook asynchronous grand-central-dispatch

所以当我想要做一些异步的东西,在Facebook上发布状态并在完成发布时收到通知我的情况。我希望dispatch_group_async可以完成这项工作,但现在我已经碰壁了。

现在这是逻辑的样子。

函数功能

func saveAndPost() {
    //1. save
    dispatch_group_async(group, queue) { () -> Void in
        print("saving to DB")
        //some func
        print("saved to DB")
    }
    //2. post
    dispatch_group_async(group, queue, { () -> Void in
        print("publishing on FB")
        //some func
        //async request to ACAccount {
            print("access")
            //async performRequestWithHandler{
                print("posted")
                //anwser from request
                }
            }
        }
        print("published on FB")
    })

    dispatch_group_notify(group, queue, { () -> Void in
        print("done")
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            //go to next view
        })
    })
}

输出

saving to DB
saved to DB
publishing on FB
published on FB
done
post
posted

我的目标是在整个发布过程完成后收到通知。也许这对dispatch_group_async是不可能的,我必须使用KVO甚至是PromiseKit?

大卫让我思考,dispatch_group_enter& 'dispatch_group_leave'正确我所需要的。所以此刻我的逻辑就像这样。

func saveAndPost() {
    //1. save
    dispatch_group_async(group, queue) { () -> Void in
        print("saving to DB")
        //some func
        print("saved to DB")
    }
    //2. post
    dispatch_group_enter(group)
        print("publishing on FB")
        //some func
        //async request to ACAccount {
            print("access")
            //async performRequestWithHandler{
                print("posted")
                //anwser from request
                dispatch_group_leave(group)
                }
            }
        }
        print("published on FB")

    dispatch_group_notify(group, queue, { () -> Void in
        print("done")
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            //go to next view
        })
    })
}

正如您所见,部分 2。现已修改。

1 个答案:

答案 0 :(得分:2)

我在处理异步调用时解决此问题的首选方法:

var asyncGroup = dispatch_group_create()

dispatch_group_enter(asyncGroup)
asyncCall1.start() {


  //end of callback
  dispatch_group_leave(asyncGroup)
}

dispatch_group_enter(asyncGroup)
asyncCall2.start() {

    asyncCall3.start() {

        asyncCall4.start() {

            dispatch_group_leave(asyncGroup)
        }

    }
}

dispatch_group_notify(asyncGroup, dispatch_get_main_queue(), {
    println("done")
})

asyncCall1.start() { ... }asyncCall2.start() { ... }只是为了告诉你它是如何工作的,它只是一种伪造的代码。

每个dispatch_group_enter来电都需要通过dispatch_group_leave来调平,否则您永远不会进入dispatch_group_notify阻止。