4

Trying to get return reply objects from a network call. The session is a class that is using the star scream API. I just can't seem to get this to work. It's only printing out 1 set of results which is the from the first id. What am I missing here?

let myGroup = DispatchGroup()

for i in 0 ..< marketIds.count {
    myGroup.enter()
    self.session.retrieve(withMethod: MarketKeys.key, withParameters: [MarketKeys.id: marketIds[i]], completion: { (results, error) in
        print("results \n")
        print(results!)
        myGroup.leave()
        })
    }
myGroup.notify(queue:.main) {
print("Done")
}
Usman Maqbool
  • 3,351
  • 10
  • 31
  • 48
Russell Warwick
  • 91
  • 1
  • 10
  • I think you should review `NSOperation` for this – Reinier Melian Jan 18 '18 at 14:18
  • @ReinierMelian actually, it is *not* necessary, he is missing the notifying part... Anyway, I would add a related question. – Ahmad F Jan 18 '18 at 14:20
  • You are missing the "notifying" part. Related: https://stackoverflow.com/a/41809248/5501940 – Ahmad F Jan 18 '18 at 14:20
  • what does session.retreive do? – Scriptable Jan 18 '18 at 14:25
  • I would start by making sure that `marketIds.count` is actually greater than 1. Add a print statement after the call to `enter` and make sure you're looping as much as you think you are. (Side note, this should be `for id in marketIds` rather than using subscripting. Subscripting works, but it creates more oppotunities for your app to crash. But this has nothing to do with your problem.) – Rob Napier Jan 18 '18 at 15:04
  • I know I was just using the "i" to print the count of the for loop to check – Russell Warwick Jan 18 '18 at 15:15

2 Answers2

5

This article gives you a quick reference guide to simple DispatchGroup use.

An example:

let dispatchGroup = DispatchGroup()

dispatchGroup.enter()
longRunningFunction { dispatchGroup.leave() }

dispatchGroup.enter()
longRunningFunctionTwo { dispatchGroup.leave() }

dispatchGroup.notify(queue: .main) {
    print("Both functions complete ")
}

The notify function is called when all items in the queue have been processed and allows you to react to this accordingly. So the example above will run two long running tasks and then will output "Both functions complete "

Scriptable
  • 19,402
  • 5
  • 56
  • 72
0

Add this so notification to group can be sent

 myGroup.notify(queue: .main) {
   print("Both functions complete ")
  }
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87