Created
April 29, 2019 13:17
-
-
Save TucoBZ/c4785e9d2d61be41d18d2be5651cef34 to your computer and use it in GitHub Desktop.
Get image from URL thread safe
This file contains hidden or 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
// | |
// 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