Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rintoandrews90/03dc6a3f3bde0ef73ff1c843734c8fd4 to your computer and use it in GitHub Desktop.
Save rintoandrews90/03dc6a3f3bde0ef73ff1c843734c8fd4 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