Skip to content

Instantly share code, notes, and snippets.

@TucoBZ
Created April 29, 2019 13:17
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 TucoBZ/c4785e9d2d61be41d18d2be5651cef34 to your computer and use it in GitHub Desktop.
Save TucoBZ/c4785e9d2d61be41d18d2be5651cef34 to your computer and use it in GitHub Desktop.
Get image from URL thread safe
//
// UIImageView+Nuke.swift
//
//
// Created by Aline e Tulio on 29/04/19.
// Copyright © 2019 . All rights reserved.
//
import UIKit
import Nuke
public extension UIImageView {
private static var kAssociationKeyImageTask = [String: ImageTask?]()
var task: ImageTask? {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UIImageView.kAssociationKeyImageTask[tmpAddress] ?? nil
}
set(newValue) {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UIImageView.kAssociationKeyImageTask[tmpAddress] = newValue
}
}
public func setImage(with url: URL, placeholder: UIImage? = nil, callback: ((Error?) -> Void)? = nil) {
task?.cancel()
task = ImagePipeline.shared.loadImage(with: url, progress: nil) { (imageResponse, responseError) in
if let error = responseError {
self.image = placeholder
guard let safeCallback = callback else { return }
safeCallback(error)
print("Job failed: \(error.localizedDescription)")
} else {
DispatchQueue.main.async {
UIView.animate(withDuration: 1.0, animations: {
self.image = imageResponse?.image
guard let safeCallback = callback else { return }
safeCallback(nil)
})
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment