等待两个异步完成函数完成,然后再执行下一行代码
我有两个函数:func Females_NonChat()
和func males_NonChat()
我想在执行viewdidload中的print语句之前等待它们两个完成。我是否需要另一个完成处理程序来完成该操作等待两个异步完成函数完成,然后再执行下一行代码
使用这些功能是请求从在线数据库中的信息火力完成处理...
override func viewDidLoad() {
super.viewDidLoad()
func Females_NonChat()
func males_NonChat()
print("finished executing both asynchronous functions")
}
func Females_NonChat(){
Anon_Ref.child("Chatting").child("female").observeSingleEventOfType(.Value, withBlock: {(snapshot) in
if let FemInChatting = snapshot.value as? [String : String] {
print("executing")
}
})
}
func males_NonChat(){
Anon_Ref.child("Chatting").child("male").observeSingleEventOfType(.Value, withBlock: {(snapshot) in
print("executing")
})
}
通常你会使用一个调度组,每个异步方法之前进入组,建成后离开该组然后在所有“输入”呼叫通过相应的“离开”呼叫匹配时设置组通知:
override func viewDidLoad() {
super.viewDidLoad()
let group = dispatch_group_create()
dispatch_group_enter(group)
Females_NonChat() {
dispatch_group_leave(group)
}
dispatch_group_enter(group)
males_NonChat() {
dispatch_group_leave(group)
}
dispatch_group_notify(group, dispatch_get_main_queue()) {
print("finished executing both asynchronous functions")
}
}
func Females_NonChat(completionHandler:() ->()) {
Anon_Ref.child("Chatting").child("female").observeSingleEventOfType(.Value) { snapshot in
if let FemInChatting = snapshot.value as? [String : String] {
print("executing")
}
completionHandler()
}
}
func males_NonChat(completionHandler:() ->()) {
Anon_Ref.child("Chatting").child("male").observeSingleEventOfType(.Value) { snapshot in
print("executing")
completionHandler()
}
}
我想这个,但由于某种原因,我的功能没有被调用。我是否也必须给他们打电话? –
发现问题。问题是,在你的代码中,你创建了dispatch_group_enter块 –
的函数,你说'func males_NonChat()',但它应该是'males_NonChat()' –
什么是'func Females_NonChat(); func males_NonChat()'在'viewDidLoad'中?这甚至不合法Swift。提供代码_compiles_(如果可以的话)。 – matt
我想说这是一个总重复http://*.com/questions/11909629/waiting-until-two-async-blocks-are-executed-before-starting-another-block?rq=1,其中首先出现在相关列表中。你甚至在询问之前尝试搜索? – matt
@matt就我所知我们可以在Swift中使用嵌套函数,所以函数可以包含另一个函数,不是吗? –