Skip to content

Instantly share code, notes, and snippets.

@StanislavK
Created September 1, 2017 09:30
Show Gist options
  • Save StanislavK/fda6c95e016592adec1344d648a2219e to your computer and use it in GitHub Desktop.
Save StanislavK/fda6c95e016592adec1344d648a2219e to your computer and use it in GitHub Desktop.
import Foundation
class TaskManager {
static let shared = TaskManager()
let session = URLSession(configuration: .default)
typealias completionHandler = (Data?, URLResponse?, Error?) -> Void
var tasks = [URL: [completionHandler]]()
func dataTask(with url: URL, completion: @escaping completionHandler) {
if tasks.keys.contains(url) {
tasks[url]?.append(completion)
} else {
tasks[url] = [completion]
let _ = session.dataTask(with: url, completionHandler: { [weak self] (data, response, error) in
DispatchQueue.main.async {
print("Finished network task")
guard let completionHandlers = self?.tasks[url] else { return }
for handler in completionHandlers {
print("Executing completion block")
handler(data, response, error)
}
}
}).resume()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment