Swift 4 arithmetic call with for loop is done using DispatchGroup, DispatchQueue and DispatchSemaphore

I want to run the for loop in quick order , DispatchGroup will kill them together, so I want to use DispatchQueue and DispatchSemaphore to achieve my goal. I could not make my program work, how to make them wait and run one after another?

let dispatchGroup = DispatchGroup() let dispatchQueue = DispatchQueue(label: "taskQueue") let dispatchSemaphore = DispatchSemaphore(value: 1) for c in self.categories { dispatchSemaphore.wait() dispatchQueue.async(group: dispatchGroup) { if let id = c.categoryId { dispatchGroup.enter() self.downloadProductsByCategory(categoryId: id) { success, data in if success, let products = data { self.products.append(products) } dispatchSemaphore.signal() dispatchGroup.leave() } } } } dispatchGroup.notify(queue: dispatchQueue) { self.refreshOrderTable { _ in self.productCollectionView.reloadData() NVActivityIndicatorPresenter.sharedInstance.stopAnimating() } } 



Thanks Palle , here is my final code:

 let dispatchGroup = DispatchGroup() let dispatchQueue = DispatchQueue(label: "taskQueue") let dispatchSemaphore = DispatchSemaphore(value: 0) dispatchQueue.async { for c in self.categories { if let id = c.categoryId { dispatchGroup.enter() self.downloadProductsByCategory(categoryId: id) { success, data in if success, let products = data { self.products.append(products) } dispatchSemaphore.signal() dispatchGroup.leave() } dispatchSemaphore.wait() } } } dispatchGroup.notify(queue: dispatchQueue) { DispatchQueue.main.async { self.refreshOrderTable { _ in self.productCollectionView.reloadData() } } } 
0
ios swift
Oct 21 '17 at 12:43 on
source share
1 answer

You can put the whole loop in a block instead of just loading a function in a block:

 dispatchQueue.async { for c in self.categories { if let id = c.categoryId { self.downloadProductsByCategory(categoryId: id) { success, data in if success, let products = data { self.products.append(products) } dispatchSemaphore.signal() } dispatchSemaphore.wait() } } } 



You can simplify your code using flatMap to expand product identifiers:

 for id in self.categories.flatMap({$0.categoryId}) { ... } 
+2
Oct. 21 '17 at 13:22
source share



All Articles