In my subclass of UIImageView
, I have a UIActivityIndicatorView
and a function to download images defined as so:
class FooUIImageView: UIImageView {
var activityIndicator: UIActivityIndicatorView {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
activityIndicator.hidesWhenStopped = true
activityIndicator.center = CGPoint(x: self.frame.width/2, y: self.frame.height/2)
self.addSubview(activityIndicator)
return activityIndicator
}
func downloadImageFrom(url: URL, imageMode: UIViewContentMode) {
self.activityIndicator.startAnimating()
self.activityIndicator.stopAnimating()
contentMode = imageMode
if let cachedImage = imageCache.object(forKey: url.absoluteString as NSString) as? UIImage {
self.image = cachedImage
} else {
URLSession.shared.dataTask(with: url) { data, _, error in
guard let data = data, error == nil else { return }
DispatchQueue.main.async {
if let imageToCache = UIImage(data: data) {
self.activityIndicator.stopAnimating()
self.imageCache.setObject(imageToCache, forKey: url.absoluteString as NSString)
self.image = imageToCache
} else {
self.activityIndicator.stopAnimating()
self.image = nil
}
}
}.resume()
}
activityIndicator.stopAnimating()
}
}
When running my app, the activityIndicator
starts loading - then the image is eventually displayed. However, the activityIndicator
remains onscreen and never disappears. In none of the places where I call stopAnimating()
above does the indicator actually stop animating. This is particularly confusing where I stop it right after calling it and yet it's still there.