Junior — Middle
How do you send ten network requests simultaneously using GCD?
sobes.tech AI
Answer from AI
To send ten network requests simultaneously using GCD (Grand Central Dispatch) in iOS, you can create a DispatchGroup and add asynchronous requests to it. This allows all requests to run in parallel and track their completion.
Example in Swift:
let dispatchGroup = DispatchGroup()
for i in 1...10 {
dispatchGroup.enter()
let url = URL(string: "https://example.com/request\(i)")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
// Handle response
print("Request \(i) completed")
dispatchGroup.leave()
}
task.resume()
}
dispatchGroup.notify(queue: .main) {
print("All requests completed")
}
This approach allows efficient management of parallel tasks and executing code after all requests are finished.