这里是请求顺序 1...10
, 但是获取的结果无序
, 随机获取到请求结果
如果打开 dispatchSemaphore
代码就会按着请求顺序进行依次返回结果
func orderByOrder(){
let dispatchGroup = DispatchGroup()
let dispatchQueue = DispatchQueue(label:"taskQueue")
for c in 1...10 {
dispatchGroup.enter()
dispatchQueue.async {
// let dispatchSemaphore = DispatchSemaphore(value: 0)
URLSession.shared.dataTask(with: URLRequest(url: URL(string: "https://www.baidu.com")!)) { data, response, error in
print("dataOrder: \(c)")
// dispatchSemaphore.signal()
dispatchGroup.leave()
}.resume()
// dispatchSemaphore.wait()
}
}
dispatchGroup.wait()
print("end")
dispatchGroup.notify(queue: dispatchQueue) {
DispatchQueue.main.async { print("end2") }
}
}
dispatchGroup.wait()
和 dispatchGroup.notify
都是通知所有请求已经完成, 做后续处理