Forked from chriswebb09/ImageDownloadProtocol.swift
Created
September 3, 2019 22:08
-
-
Save indyfromoz/0be7a2638a819ae402ce5d4150d8c7f2 to your computer and use it in GitHub Desktop.
Download on Thread
This file contains 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 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() | |
} | |
} | |
} |
This file contains 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 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