iOS - Swift 3 - Dispatchgroup

iOS - swift 3 - DispatchGroup

I think you need to put self.dispatchGroup.leave() inside the Alamofire response handler. As written, you leave as soon as you queue the request.

    queue.async(group: dispatchGroup) {
Alamofire.request(Content.url).responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
// do some stuff and save to Content struct
Content.annotations += [Station(...)]

case .failure(let error):
print("error: ",error)

Using DispatchGroup() in Swift 3 to perform a task?

With hint provided in the comment and solution found here: from @vadian, since I am only performing one task, I used a async completion handler:

Second Class:

func checkSpeed(completion: @escaping () -> ())
// call other functions and perform task to download file from link

// print out speed of download

nMbps = speedOfDownload


First Class:

let check: SecondClass = SecondClass()

check.checkSpeed {
print("speed = \(check.nMbps)")


Now checkSpeed will complete first and speed is assigned the appropriate value.

How to use Dispatch Group in a loop with asynchronous Function Swift?

Leave within the async block not outside of it ... and enter should be equal to leave so put it in defer statement to always execute before leaving the scope

  func Promise_searchedDataFromDB(stringArray:[String]) {
for id in stringArray {
collectionRef.getDocuments { (querySnapshot, error) in
defer{ myGroup.leave() }

if error != nil {
else {
guard let snapshot = querySnapshot else {return}
for document in snapshot.documents {

let myData =
if StaticVariable == true {

self.typeOfListing = myData["Type"] as? String ?? "Not Found"
self.charges = Int(myData["Charges"] as? String ?? "Not Found") ?? 0
self.nameOfListing = myData["Title"] as? String ?? "Not Found"
self.currency = myData["Currency"] as? String ?? "Not Found"
self.days = myData["Days"] as? String ?? "Not Found"
self.details = myData["Description"] as? String ?? "Not Found"
self.cityName = myData["City"] as? String ?? "Ghost"

let dataArray = CellComponents(image: UIImage(named: "b")!, typeOfListing: self.typeOfListing , charges: self.charges, rating: 4.1, nameOfListing: self.nameOfListing , cityName: self.cityName, detail: self.details, currency: self.currency, days: self.days)


myGroup.notify(queue: .main) {
print("All done")

Why DispatchGroup is not working correctly

The leave line must be inside the completion closure

func getMenu() {
let menu = self.ref.collection("menu").document("menu1")
menu.getDocument(source: .cache) { (document, error) in
if let document = document {
let menuName = document.get("menuEngName") as! String
print("MenuName = \(menuName)")
} else {
print("Document does not exist in cache")

Related Topics

Leave a reply