Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indyfromoz/0be7a2638a819ae402ce5d4150d8c7f2 to your computer and use it in GitHub Desktop.
Save indyfromoz/0be7a2638a819ae402ce5d4150d8c7f2 to your computer and use it in GitHub Desktop.
Download on Thread
import UIKit
protocol ImageDownloadProtocol {
func downloadImage(from url: URL, completion: @escaping (UIImage?) -> Void)
}
extension ImageDownloadProtocol {
func downloadImage(from url: URL, completion: @escaping (UIImage?) -> Void) {
let session = URLSession(configuration: .default)
DispatchQueue.global(qos: .background).async {
print("In background")
session.dataTask(with: URLRequest(url: url)) { data, response, error in
if error != nil {
print(error?.localizedDescription ?? "Unknown error")
}
if let data = data, let image = UIImage(data: data) {
print("Downloaded image data")
DispatchQueue.main.sync {
print("Dispatched to main")
completion(image)
}
}
}.resume()
}
}
}
import UIKit
class ViewControllerOne: UIViewController {
let imageViewOne = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
imageViewOne.frame = UIScreen.main.bounds
view.addSubview(imageViewOne)
setImage()
}
}
extension ViewControllerOne: ImageDownloadProtocol {
func setImage() {
let url = URL(string: "http://cdn-www.dailypuppy.com/dog-images/colby-the-golden-retriever_77539_2016-09-16_w450.jpg")!
downloadImage(from: url) { image in
if Thread.isMainThread {
print("Thread is main")
}
self.imageViewOne.image = image
print("Done")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment