Swift DispatchSemaphore正在冻结应用程序



我尝试使用DispatchSemaphore在循环中运行API服务,它会冻结应用程序,我的要求是我调用API来获取细节列表每个细节我有不同的请求使用我需要在循环中调用API,每个API都依赖于前一个API的响应因此我使用DispatchSemaphore等待和信号方法但它正在释放应用程序

示例代码:

func DownloadInformation(urlString: String, device: String, indexValue: Int, completion: @escaping (_ requestIndex: Int?) -> (Void)) {
ApiService.sharedInstance.DownloadHealthInsightDetails(ID: self.equipmentAnalaysisArr[indexValue].id) { [self] (serverResponse, error, cardID) -> (Void) in
if(serverResponse != nil && error == nil) {
let insightCycleList = serverResponse as? NSDictionary
if (insightCycleList?["error"]) == nil {

if let cycle = insightCycleList?["cycles"] as? [AnyObject], cycle.count != 0 {
let dispatchGroup = DispatchGroup()
let dispatchQueue = DispatchQueue(label: "taskQueue")
let dispatchSemaphore = DispatchSemaphore(value: 0)
for i in 0..<cycle.count {
if i < 5 {
dispatchGroup.enter()
let element = cycle[i]
      
self.DownloadCycleData(urlString: blob_url , cycleDownloadCompletion: {_ in
completion(indexValue)
dispatchSemaphore.signal()
dispatchGroup.leave()
})
dispatchSemaphore.wait()
}
}

dispatchGroup.notify(queue: DispatchQueue.main) {
print("done")
}
//                        }
} else {
self.ShowMessage(index: indexValue, message: self.message)
}
}else {
self.ShowMessage(index: indexValue, message: self.message)
}
}
}
}
谁能给我一些建议来解决这个问题?

谢谢。

您没有使用DispatchQueue(label: "taskQueue")。但是对于这种情况,也许您应该考虑使用某种状态机。

if let cycle = insightCycleList?["cycles"] as? [AnyObject], cycle.count != 0 {
let dispatchQueue = DispatchQueue(label: "taskQueue")
let semaphore = DispatchSemaphore(value: 0)
dispatchQueue.async {
for i in 0..<cycle.count {
if i < 5 {
let cycleSemaphore = DispatchSemaphore(value: 0)
let element = cycle[i]
self.DownloadCycleData(urlString: blob_url , cycleDownloadCompletion: {_ in
completion(indexValue)
cycleSemaphore.signal()
})
cycleSemaphore.wait()
}
}
semaphore.signal()
}
semaphore.wait()
}