group dispatch swift code example

Example: DispatchGroup example swift

class DispatchGroupExample: UIViewController {
  private let dispatchGroup = DispatchGroup()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    fetchData(url: xxx)
    fetchData(url: yyy)
    
    // 3: notify job done
    dispatchGroup.notify(queue: .main) {
      self.goToNext()
    }
  }
  
  private func fetchData(url: URL) {
    // 1: enter group
    dispatchGroup.enter()
    
    URLSession.shared.dataTask(with: url) { 
      [weak self] (data, urlResponse, error) in
      	// parse data
      	...
      
      	// 2: leave group
      	self?.dispatchGroup.leave()
    }
  }
}