Skip to content

Instantly share code, notes, and snippets.

@rhlsthrm
Last active May 29, 2020 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rhlsthrm/65232eed341993277406b1bdedf661ac to your computer and use it in GitHub Desktop.
Save rhlsthrm/65232eed341993277406b1bdedf661ac to your computer and use it in GitHub Desktop.
Swift code to use raw Grand Central Dispatch to make requests
import Foundation
var todos = [String: Any]()
let dispatchGroup = DispatchGroup()
for todo in 0..10 {
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/\(todo)")
dispatchGroup.enter()
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
let jsonSerialized = try! JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
todos += [jsonSerialized]
// do more stuff
// ready to end processing on this particular async task?
dispatchGroup.leave()
}
task.resume()
}
dispatchGroup.notify(queue: DispatchQueue.main) {
print("Got \(todos.count) todos!")
// other stuff including display on screen
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment