Last active
March 22, 2023 12:51
-
-
Save ninja342/a372c8139da505f8e2269415c5bdc99f to your computer and use it in GitHub Desktop.
Swift Network Image
This file contains 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
// You can use this class to download images for UICollectionViewCells or UITableViewCells with no worries about cell reusage | |
import UIKit | |
class NetworkImageView: UIImageView { | |
private var imageDownloadTask: URLSessionDataTask? | |
private var activityIndicator: UIActivityIndicatorView? | |
public func imageFromURL(url: URL) { | |
imageDownloadTask?.cancel() // cancel the previous task if exists | |
activityIndicator?.removeFromSuperview() // if activity indicator exists remove it from superview | |
if self.image == nil { | |
activityIndicator = UIActivityIndicatorView(style: .medium) // We are sure that activity indicator exists after this line so force unwrapping is safe | |
activityIndicator!.translatesAutoresizingMaskIntoConstraints = false | |
self.addSubview(activityIndicator!) | |
activityIndicator!.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true | |
activityIndicator!.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true | |
activityIndicator!.startAnimating() | |
} | |
imageDownloadTask = URLSession.shared.dataTask(with: url, completionHandler: { [weak self] (data, response, error) -> Void in | |
if let error = error { | |
print(error) | |
return | |
} | |
DispatchQueue.main.async(execute: { () -> Void in | |
let image = UIImage(data: data!) | |
self?.activityIndicator?.removeFromSuperview() | |
self?.image = image | |
}) | |
}) | |
imageDownloadTask?.resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment