Created
June 25, 2018 05:47
-
-
Save pawankmrai/62bd7f78897983c08beb627d71692b88 to your computer and use it in GitHub Desktop.
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
| // | |
| // AppImageView.swift | |
| // Socho | |
| // | |
| // Created by Pawan on 06/06/18. | |
| // Copyright © 2018 Pawan. All rights reserved. | |
| // | |
| import Foundation | |
| import UIKit | |
| import SnapKit | |
| extension UIImageView { | |
| func loadImage(_ fromUrl: URL, placeHolderImage: UIImage) { | |
| // Image caching | |
| let cache = URLCache.shared | |
| // Loading indicator | |
| let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) | |
| indicator.hidesWhenStopped = true | |
| self.addSubview(indicator) | |
| // Constraints | |
| indicator.snp.makeConstraints { (make) in | |
| make.centerX.equalToSuperview() | |
| make.centerY.equalToSuperview() | |
| } | |
| // | |
| indicator.startAnimating() | |
| // Make request | |
| let request = URLRequest(url: fromUrl) | |
| // Check if image is cached | |
| if let data = cache.cachedResponse(for: request)?.data, let image = UIImage(data: data) { | |
| DispatchQueue.main.async { | |
| indicator.stopAnimating() | |
| self.image = image | |
| } | |
| } else { | |
| let session = URLSession.shared | |
| let dataTask = session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in | |
| // Set defaut image if error occured | |
| if let error = error { | |
| print(error) | |
| DispatchQueue.main.async { | |
| indicator.stopAnimating() | |
| self.image = placeHolderImage | |
| } | |
| } | |
| // Cache image data to reuse for same request | |
| if let data = data, let response = response, ((response as? HTTPURLResponse)?.statusCode ?? 500) < 300, let image = UIImage(data: data) { | |
| let cachedData = CachedURLResponse(response: response, data: data) | |
| cache.storeCachedResponse(cachedData, for: request) | |
| // | |
| DispatchQueue.main.async { | |
| indicator.stopAnimating() | |
| self.image = image | |
| } | |
| } | |
| } | |
| dataTask.resume() | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment