Lazy loading FIRStorage images with FirebaseCollectionViewDataSource (Swift)?
I'm currently setting images within populateCellWithBlock using a FIRStorage ref and dataWithMaxSize method. The images show, but as you scroll, there is a flicker of a previous image from the reused cell.
self.dishesSource.populateCellWithBlock() {
let cell = $0 as! dishCVCell
let dish = $1 as! Dish
let dishImgRef = FIRStorage.storage().referenceForURL(dish.imageURL)
dishImgRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
if (error != nil) {
print(error)
} else {
cell.dishPhoto.image = UIImage.init(data: data!)
}
}
}
To avoid having a previous image flicker, I've set the image to nil in the prepareForReuse method within my custom CollectionView Cell:
override func prepareForReuse() {
dishPhoto.image = nil
}
It works, but I was wondering if there was a more efficient/lazy loading way to load cell images in the background when using FirebaseUI FirebaseCollectionViewDataSource?
That sounds about right, I don't think your code can be more efficient/lazy than it currently is since there's no way to know what data will go in which cell until that cell is about to be presented.
A few things to note, though:
- Looks like we don't document whether or not
dataWithMaxSize(completion:)will execute its callback closure on the main thread or not, which is important here because you're setting UI stuff in that closure. Our docs have been kinda suffering, hopefully we get to that soon... :( - If your client is on really bad internet and
dataWithMaxSize(completion:)takes a long time to finish, it may be possible for a stale callback block to present the wrong image on a cell. Also, if the user scrolls very quickly, you'll queue up a whole bunch of image downloads even though the amount of images you end up presenting doesn't actually increase. To fix these two issues you should cancel downloads if they're still running and the cell they should go into has scrolled off the screen. prepareForReuse()requires asupercall.
This sort of question is generally better suited for the StackOverflow format, but I'm answering it here because it's an especially common use pattern and it reflects flaws in our docs I'd like to fix at some point.
Gonna close this since it hasn't been active in a while.