Skip to content

Instantly share code, notes, and snippets.

@trupin
Last active February 16, 2019 18:05
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save trupin/2af927f90c773b459fd15550ea50f1e5 to your computer and use it in GitHub Desktop.
import UIKit
final class ImageManager {
// weaver: urlSession = URLSession
// weaver: urlSession.builder = URLSession.make
private let dependencies: ImageManagerDependencyContainer
required init(dependencies: ImageManagerDependencyContainer) {
self.dependencies = dependencies
}
func getImage(with path: String, completion: @escaping (UIImage?) -> Void) {
let completionOnMainThread = { result in
DispatchQueue.main.async {
completion(result)
}
}
guard let url = URL(string: "https://image.tmdb.org/t/p/w1280/\(path)") else {
completion(nil)
return
}
let task = dependencies.urlSession.dataTask(with: url) { (data, response, error) in
if error != nil {
completionOnMainThread(nil)
return
}
guard let response = response as? HTTPURLResponse else {
completionOnMainThread(nil)
return
}
guard response.statusCode == 200 || response.statusCode == 304 else {
completionOnMainThread(nil)
return
}
guard let data = data else {
completionOnMainThread(nil)
return
}
completionOnMainThread(UIImage(data: data))
}
task.resume()
}
}
extension URLSession {
static func make(_: ImageManagerDependencyResolver) -> URLSession {
return URLSession(configuration: .default)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment