起源
- 有一個(gè)界面的數(shù)據(jù)需要涉及多個(gè)網(wǎng)絡(luò)請求垮衷,然后等所有網(wǎng)絡(luò)請求完成后統(tǒng)一處理數(shù)據(jù)
代碼
// MARK: 網(wǎng)絡(luò)請求調(diào)度組
func datesRequestGroup(_ pickpickId: String){
let group = DispatchGroup()
let groupQueue = DispatchQueue(label: "hot_comment_requst")
// 網(wǎng)絡(luò)請求A
group.enter()
groupQueue.async {
CommentService.init().hotCommentInfo(withPickPickId: pickpickId) { (responseData, code, responseString) in
guard code == 200 else {
group.leave()
return
}
self.hotCommentBaseData = CommentBaseData.model(with: responseData)
guard let list = self.hotCommentBaseData?.data else {
group.leave()
return
}
self.hotcomments.removeAll()
self.hotcomments = self.commentDataHandle(list, isHotComment: true)
group.leave()
}
}
// 網(wǎng)絡(luò)請求B
group.enter()
groupQueue.async {
UserService.init().queryPickItemCommentList(withPickId: pickpickId, scroll: "") { (responseObject, code, responseString) in
guard code == 200 else {
group.leave()
return
}
self.commentsBaseData = CommentBaseData.model(with: responseObject)
guard let list = self.commentsBaseData?.data else {
group.leave()
return
}
self.comments.removeAll()
self.comments = self.commentDataHandle(list)
}
}
// 調(diào)度組里的任務(wù)都執(zhí)行完畢執(zhí)行
group.notify(queue: groupQueue) {
self.totalList.removeAll()
self.totalList = self.hotcomments + self.comments
}
}
注意
-
group.enter()
和group.leave()
必須成對出現(xiàn)