Skip to content

Commit

Permalink
Add cached image data for token's icon
Browse files Browse the repository at this point in the history
  • Loading branch information
manhlx3006 committed Jan 9, 2020
1 parent 445d8b5 commit 2e27377
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
10 changes: 9 additions & 1 deletion KyberNetwork/KyberNetwork/Extensions/UIButton+Kyber.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,18 @@ extension UIButton {
size: CGSize? = nil,
state: UIControlState = .normal
) {
if let cachedImg = UIImage.imageCache.object(forKey: url as AnyObject) as? UIImage {
self.setImage(cachedImg.resizeImage(to: size), for: .normal)
self.layoutIfNeeded()
return
}
self.setImage(placeHolder?.resizeImage(to: size), for: state)
URLSession.shared.dataTask(with: url) { (data, _, error) in
self.layoutIfNeeded()
URLSession.shared.dataTask(with: url) { [weak self] (data, _, error) in
guard let `self` = self else { return }
if error == nil, let data = data, let image = UIImage(data: data) {
DispatchQueue.main.async {
UIImage.imageCache.setObject(image, forKey: url as AnyObject)
self.setImage(image.resizeImage(to: size), for: .normal)
self.layoutIfNeeded()
}
Expand Down
3 changes: 3 additions & 0 deletions KyberNetwork/KyberNetwork/Extensions/UIImage+Kyber.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import UIKit
import JdenticonSwift

extension UIImage {

static let imageCache = NSCache<AnyObject, AnyObject>()

static func generateQRCode(from string: String) -> UIImage? {
let context = CIContext()
let data = string.data(using: String.Encoding.ascii)
Expand Down
10 changes: 9 additions & 1 deletion KyberNetwork/KyberNetwork/Extensions/UIImageView+Kyber.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,18 @@ import UIKit

extension UIImageView {
func setImage(with url: URL, placeholder: UIImage?, size: CGSize? = nil, applyNoir: Bool = false) {
if let cachedImg = UIImage.imageCache.object(forKey: url as AnyObject) as? UIImage {
self.image = applyNoir ? cachedImg.resizeImage(to: size)?.noir : cachedImg.resizeImage(to: size)
self.layoutIfNeeded()
return
}
self.image = applyNoir ? placeholder?.resizeImage(to: size)?.noir : placeholder?.resizeImage(to: size)
URLSession.shared.dataTask(with: url) { (data, _, error) in
self.layoutIfNeeded()
URLSession.shared.dataTask(with: url) { [weak self] (data, _, error) in
guard let `self` = self else { return }
if error == nil, let data = data, let image = UIImage(data: data) {
DispatchQueue.main.async {
UIImage.imageCache.setObject(image, forKey: url as AnyObject)
self.image = applyNoir ? image.resizeImage(to: size)?.noir : image.resizeImage(to: size)
self.layoutIfNeeded()
}
Expand Down

0 comments on commit 2e27377

Please sign in to comment.