我正在尝试等待来自不同类的所有函数完成将数据附加到数组后再继续。
我为dispath组创建了一个singleton类。当来自不同类的所有组都离开时,它不会通知result((,而是单独执行。
class parralelRunner {
let dispatchGroup = DispatchGroup()
result(){
dispatchGroup.notify(queue: .main) {
print("All functions complete 👍")
}
}
}
class run1 {
func start(){
callAPI(){
filterresult()
}
}
callAPI(completion: (JSON)){
Alamofire.request("url", headers: headers).responseJSON { response in
if response.result.isSuccess{
completion(JSON(response.result.value!))
}else{
print("Binance - Couldn't import Request: Please check your internet connection")
}
}
}
func filterresult(){
parralelRunner.dispatchGroup.enter()
for .... {
}
parralelRunner.dispatchGroup.leave()
parralelRunner.result()
}
}
class run2 {
func start(){
callAPI(){
filterresult()
}
}
callAPI(completion: (JSON)){
Alamofire.request("url", headers: headers).responseJSON { response in
if response.result.isSuccess{
completion(JSON(response.result.value!))
}else{
print("Binance - Couldn't import Request: Please check your internet connection")
}
}
}
func filterresult(){
parralelRunner.dispatchGroup.enter()
for .... {
}
parralelRunner.dispatchGroup.leave()
parralelRunner.result()
}
}
对parralelRunner.result()
的调用只能调用一次。并且需要在每个异步进程开始时对enter
进行调用,并在调用完成后对leave
进行相应的调用。
您需要做的第一件事是将run1
和run2
重构为以下内容:
class run1 {
func start(){
parralelRunner.dispatchGroup.enter()
callAPI(){ JSON in
if let JSON = JSON {
filterresult()
}
parralelRunner.dispatchGroup.leave()
}
}
callAPI(completion: (JSON?)){
Alamofire.request("url", headers: headers).responseJSON { response in
if response.result.isSuccess{
completion(JSON(response.result.value!))
}else{
print("Binance - Couldn't import Request: Please check your internet connection")
completion(nil)
}
}
}
func filterresult() {
for .... {
}
}
}
那么,无论使用run1
和run2
,都需要类似的东西:
run1.start()
run2.start()
parralelRunner.result()