Last active
July 29, 2018 18:43
-
-
Save alastairparagas/5f9af4330921682b3ffebb3cc8733b08 to your computer and use it in GitHub Desktop.
Multithreaded requests in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| import Dispatch | |
| func getRequestTask(url: String, dispatchGroup: DispatchGroup) { | |
| dispatchGroup.enter() | |
| let request = URLRequest(url: URL(string: url)!) | |
| let task = URLSession(configuration: URLSessionConfiguration.default).dataTask( | |
| with: request, | |
| completionHandler: { | |
| (data, response, error) in | |
| if let data = data { | |
| if let dataAsString = String(data: data, encoding: .utf8) { | |
| print(dataAsString) | |
| dispatchGroup.leave() | |
| return | |
| } | |
| } | |
| print("Something terrible has happened!") | |
| dispatchGroup.leave() | |
| } | |
| ) | |
| task.resume() | |
| } | |
| let requestDispatchGroup = DispatchGroup() | |
| for url in [ | |
| "https://jsonplaceholder.typicode.com/posts", | |
| "https://jsonplaceholder.typicode.com/comments", | |
| "https://jsonplaceholder.typicode.com/albums" | |
| ] { | |
| getRequestTask(url: url, dispatchGroup: requestDispatchGroup) | |
| } | |
| requestDispatchGroup.wait() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment