Skip to content

Instantly share code, notes, and snippets.

@paskowski
Last active March 7, 2018 10:49
Show Gist options
  • Save paskowski/f2fa85fde45f398474ee59825b9ffb24 to your computer and use it in GitHub Desktop.
Save paskowski/f2fa85fde45f398474ee59825b9ffb24 to your computer and use it in GitHub Desktop.
import UIKit
class AsyncImageDownloadOperation: AsyncOperation {
var downloadedImage: UIImage?
override func main() {
let defaultSession = URLSession(configuration: .default)
guard let imgUrl = URL(string: "https://unsplash.com/photos/M9O6GRrEEDY/download?force=true") else { return }
let dataTask = defaultSession.dataTask(with: imgUrl) { (data, response, error) in
if let error = error {
print("Image download encountered an error: \(error.localizedDescription)")
} else if let data = data, let response = response as? HTTPURLResponse,
response.statusCode == 200 {
if self.isCancelled {
self.state = .finished
return
}
let image = UIImage(data: data)
self.downloadedImage = image
self.state = .finished
}
}
dataTask.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment