Skip to content

Instantly share code, notes, and snippets.

@saoudrizwan
Last active May 10, 2024 10:56
Show Gist options
  • Save saoudrizwan/dd25978e82eba27138361c5a2b5c4457 to your computer and use it in GitHub Desktop.
Save saoudrizwan/dd25978e82eba27138361c5a2b5c4457 to your computer and use it in GitHub Desktop.
Handle multiple network requests with the same URL efficiently with a shared task manager
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