swift: load the image data in background - ios

I need to load 100 images in cells. If I use this method in tableView cellForRowAt:
cell.cardImageView.image = UIImage(named: "\(indexPath.row + 1).jpg")
and start scrolling fast my tableView freezes.
I use this method to load the image data in background that fix freezes:
func loadImageAsync(imageName: String, completion: #escaping (UIImage) -> ()) {
DispatchQueue.global(qos: .userInteractive).async {
guard let image = UIImage(named: imageName) else {return}
DispatchQueue.main.async {
completion(image)
}
}
}
in tableView cellForRowAt call this:
loadImageAsync(imageName: "\(indexPath.row + 1).jpg") { (image) in
cell.cardImageView.image = image
}
But I have one bug may arise in this approach, such that while scrolling fast I may see old images for a while. How to fix this bug?

Your cells are being reused.
When cell goes out of screen it gets to internal UITableViews reuse pool, and when you dequeueReusableCell(withIdentifier:for:) in tableView(_:cellForRowAt:) you get this cell again (see, "reusable" in name). It is important to understand UITableViewCell's life cycle. UITableView does not hold 100 living UITableViewCells for 100 rows, that would kill performance and leave apps without memory pretty soon.
Why do you see old images in your cells?
Again, cells are being reused, they keep their old state after reuse, you'll need to reset the image, they won't reset it by themselves. You can do that when you configure a new cell or detect when the cell is about to be reused.
As simple as:
cell.cardImageView.image = nil // reset image
loadImageAsync(imageName: "\(indexPath.row + 1).jpg") { (image) in
cell.cardImageView.image = image
}
The other way is detecting reuse and resetting. In your cell subclass:
override func prepareForReuse() {
super.prepareForReuse()
self.cardImageView.image = nil // reset
}
Why do you see wrong images in your cells? By the time completion closure sets image into cardImageView, UITableViewCell has been reused (maybe, even, more than once). To prevent this you could test if you're setting image in the same cell, for example, store image name with your cell, and then:
// naive approach
let imageName = "\(indexPath.row + 1).jpg"
cell.imageName = imageName
loadImageAsync(imageName: imageName) { (image) in
guard cell.imageName == imageName else { return }
cell.cardImageView.image = image
}
There is a lot of stuff to take care of when designing lists, I won't be going into much detail here. I'd suggest to try the above approach and investigate the web on how to handle performance issues with lists.

in your cell class you need to declare
override func prepareForReuse() {
super.prepareForReuse()
}
to prepare the cell for the reuse

Related

What is the simplest way to insert resized images from Core Data into a UICollectionView?

When I set images from a local array into each collection view cell, scrolling is laggy. This is because the full scaled UIImage is being used when the cell will be displayed.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
let image = images[indexPath.row]
cell.imageView.image = image
return cell
}
In order to try and solve this, I wrote a method that resizes images to their proper size at runtime.
private func resizeImages(images: [UIImage], size: CGSize) -> [UIImage?] {//...}
But resizing all the images in the array in viewDidLoad took a considerable amount of time.
This is a simple photo album app so I would prefer avoiding any use of activity or loading indicators. Given access to image data fetched from Core Data, how can I set the images in a collection view such that it won't lag while scrolling?
Instead of resizing images on runtime you should do this task at time of saving in CoreData. Instead of saving one image, you should store two images. One with full scale (high resolution) and other thumbnail (resized). Load only thumbnails in your CollectionViewCell to avoid scroll lagging.
I have used a LazyImageView (originally taken from cocoanetics.com) for networking which probably work without many changes in your case:
import UIKit
class LazyImageView: UIImageView {
var loading = false
weak var rawImage: UIImage?
deinit {
image = nil
loading = false
}
override func didMoveToSuperview() {
if !loading && image == nil{
loading = true
DispatchQueue.global().async {
self.resizeImage()
}
}
}
func resizeImage() {
let resizedImage: UIImage? = nil
// do the resizing
DispatchQueue.main.async {
self.image = resizedImage
self.loading = false
}
}
}
As you have asked for simple I would consider it done.
If you want to spend some more time, you could/should think about caching (i.e. to the file system's cache folder).
Depending on the app, maybe you have another nice UX way to give the user a hint what will happen (i.e. setting correct(?) placeholder color as a background for the image before loading).
Considering #Bilal answer to save a correct thumb version sound also well. It really depends on your app, i.e. if the user has a choice to resize the overall image size in the collection view (now or as a future feature).

UITableView cell is displaying an incorrect image, even while setting the image to nil as the first step in tableView.dequeueReusableCell

I'm trying to do something very basic, but the fix proposed in other similar questions does not seem to be working. I have an image cache, and a tableView. I want to display the image from the cache if it exists, otherwise there should be nothing. For some reason the tableView is still displaying a reused cell with the wrong image, even when I set the image view to nil. Below is my code:
let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell", for: indexPath) as! SearchResultsTableViewCell
cell.profilePhoto?.image = nil
cell.profilePhoto?.backgroundColor = UIColor.gray
if let userID = myObject.posterId, let profileImage = self.imageCache.object(forKey: userID as AnyObject) {
cell.profilePhoto?.image = profileImage
} else {
if let userId = myObject.posterId {
downloadImage.beginImageDownload() {
(imageOptional) in
if let image = imageOptional {
cell.profilePhoto?.image = image
self.imageCache.setObject(image, forKey: userId as AnyObject)
}
}
}
}
What am I doing wrong? I can't for the life of me figure out why the image is not being set to nil, even though I do that as the first step!
The problem is downloadImage.beginImageDownload closures are holding references to the uitableview cells.
When you complete the image download, you set cell.profilePhoto?.image property, even if the tableView recycles reusable cells to display a different row.
Assign your cell's tag to the indexPath.row and test if cell is still relevant for assigning downloaded image:
/* right after cell dequeue */
cell.tag = indexPath.row
then
/* download finished here */
if cell.tag == indexPath.row {
/* yeah, I want to rock this cell with my downloaded image! */
cell.profilePhoto?.image = downloadedImage
}
Be aware: this will only work in tableview with one section.
P.S. You can place the clean up of your cells in prepareForReuse method inside the SearchResultsTableViewCell to tidy things a little.
You appear to be setting your image to nil but have you considered the downloads which might be in flight when you reuse that cell? It looks like you could be updating a cell's image when the download for some previous index path finishes.

Swift: load images Async in UITableViewCell

I have a tableview that I created with code (without storyboard):
class MSContentVerticalList: MSContent,UITableViewDelegate,UITableViewDataSource {
var tblView:UITableView!
var dataSource:[MSC_VCItem]=[]
init(Frame: CGRect,DataSource:[MSC_VCItem]) {
super.init(frame: Frame)
self.dataSource = DataSource
tblView = UITableView(frame: Frame, style: .Plain)
tblView.delegate = self
tblView.dataSource = self
self.addSubview(tblView)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: nil)
let record = dataSource[indexPath.row]
cell.textLabel!.text = record.Title
cell.imageView!.downloadFrom(link: record.Icon, contentMode: UIViewContentMode.ScaleAspectFit)
cell.imageView!.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
print(cell.imageView!.frame)
cell.detailTextLabel!.text = record.SubTitle
return cell
}
}
and in other class I have an extension method for download images Async:
extension UIImageView
{
func downloadFrom(link link:String?, contentMode mode: UIViewContentMode)
{
contentMode = mode
if link == nil
{
self.image = UIImage(named: "default")
return
}
if let url = NSURL(string: link!)
{
print("\nstart download: \(url.lastPathComponent!)")
NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, _, error) -> Void in
guard let data = data where error == nil else {
print("\nerror on download \(error)")
return
}
dispatch_async(dispatch_get_main_queue()) { () -> Void in
print("\ndownload completed \(url.lastPathComponent!)")
self.image = UIImage(data: data)
}
}).resume()
}
else
{
self.image = UIImage(named: "default")
}
}
}
I used this function in other places and worked correctly, Based on my logs I understand that images downloaded without problem (when the cell is rendered) and after download of image, The cell UI not updated.
Also I tried to use caching library like Haneke but problem is exist and not change.
Please help me to understand mistakes
Thanks
After setting the image you should call self.layoutSubviews()
edit: corrected from setNeedsLayout to layoutSubviews
The issue is that the .subtitle rendition of UITableViewCell will layout the cell as soon as cellForRowAtIndexPath returns (overriding your attempt to set the frame of the image view). Thus, if you are asynchronously retrieving the image, the cell will be re-laid out as if there was no image to show (because you're not initializing the image view's image property to anything), and when you update the imageView asynchronously later, the cell will have already been laid out in a manner such that you won't be able to see the image you downloaded.
There are a couple of solutions here:
You can have the download update the image to default not only when there is no URL, but also when there is a URL (so you'll first set it to the default image, and later update the image to the one that you downloaded from the network):
extension UIImageView {
func download(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFill, placeholder: UIImage? = nil) {
contentMode = mode
image = placeholder
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, let response = response as? HTTPURLResponse, error == nil else {
print("error on download \(error ?? URLError(.badServerResponse))")
return
}
guard 200 ..< 300 ~= response.statusCode else {
print("statusCode != 2xx; \(response.statusCode)")
return
}
guard let image = UIImage(data: data) else {
print("not valid image")
return
}
DispatchQueue.main.async {
print("download completed \(url.lastPathComponent)")
self.image = image
}
}.resume()
}
}
This ensures that the cell will be laid out for the presence of an image, regardless, and thus the asynchronous updating of the image view will work (sort of: see below).
Rather than using the dynamically laid out .subtitle rendition of UITableViewCell, you can also create your own cell prototype which is laid out appropriately with a fixed size for the image view. That way, if there is no image immediately available, it won't reformat the cell as if there was no image available. This gives you complete control over the formatting of the cell using autolayout.
You can also define your downloadFrom method to take an additional third parameter, a closure that you'll call when the download is done. Then you can do a reloadRowsAtIndexPaths inside that closure. This assumes, though, that you fix this code to cache downloaded images (in a NSCache for example), so that you can check to see if you have a cached image before downloading again.
Having said that, as I alluded to above, there are some problems with this basic pattern:
If you scroll down and then scroll back up, you are going to re-retrieve the image from the network. You really want to cache the previously downloaded images before retrieving them again.
Ideally, your server's response headers are configured properly so that the built in NSURLCache will take care of this for you, but you'd have to test that. Alternatively, you might cache the images yourself in your own NSCache.
If you scroll down quickly to, say, the 100th row, you really don't want the visible cells backlogged behind image requests for the first 99 rows that are no longer visible. You really want to cancel requests for cells that scroll off screen. (Or use dequeueCellForRowAtIndexPath, where you re-use cells, and then you can write code to cancel the previous request.)
As mentioned above, you really want to do dequeueCellForRowAtIndexPath so that you don't have to unnecessarily instantiate UITableViewCell objects. You should be reusing them.
Personally, I might suggest that you (a) use dequeueCellForRowAtIndexPath, and then (b) marry this with one of the well established UIImageViewCell categories such as AlamofireImage, SDWebImage, DFImageManager or Kingfisher. To do the necessary caching and cancelation of prior requests is a non-trivial exercise, and using one of those UIImageView extensions will simplify your life. And if you're determined to do this yourself, you might want to still look at some of the code for those extensions, so you can pick-up ideas on how to do this properly.
--
For example, using AlamofireImage, you can:
Define a custom table view cell subclass:
class CustomCell : UITableViewCell {
#IBOutlet weak var customImageView: UIImageView!
#IBOutlet weak var customTitleLabel: UILabel!
#IBOutlet weak var customSubtitleLabel: UILabel!
}
Add a cell prototype to your table view storyboard, specifying (a) a base class of CustomCell; (b) a storyboard id of CustomCell; (c) add image view and two labels to your cell prototype, hooking up the #IBOutlets to your CustomCell subclass; and (d) add whatever constraints necessary to define the placement/size of the image view and two labels.
You can use autolayout constraints to define dimensions of the image view
Your cellForRowAtIndexPath, can then do something like:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
let record = dataSource[indexPath.row]
cell.customTitleLabel.text = record.title
cell.customSubtitleLabel.text = record.subtitle
if let url = record.url {
cell.customImageView.af.setImage(withURL: url)
}
return cell
}
With that, you enjoy not only basic asynchronous image updating, but also image caching, prioritization of visible images because we're reusing dequeued cell, it's more efficient, etc. And by using a cell prototype with constraints and your custom table view cell subclass, everything is laid out correctly, saving you from manually adjusting the frame in code.
The process is largely the same regardless of which of these UIImageView extensions you use, but the goal is to get you out of the weeds of writing the extension yourself.
oh my god, the layoutSubviews is not recommended to use directly
the right way to solve the problem is call:
[self setNeedsLayout];
[self layoutIfNeeded];
here, the two way have to call together.
try this, have a good luck.
Create your own cell by subclassing UITableViewCell. The style .Subtitle, which you are using, has no image view, even if the property is available. Only the style UITableViewCellStyleDefault has an image view.
Prefer SDWebImages library here is the link
it will download image async and cache the image also
and very easy to integrate into the project as well

Set Image in visible UITableviewCell after async download

I have a tableView with dynamic cells. Each cell has got an imageView and a textLabel. I'm working with Alamofire & AlamofireImage by the way.
My problem is that the first cells (which you see if view did appear) don't show the images. But if i scroll down i see the images of the other cells. And if scroll up again the images of the first cells appear too.
First of all i download user data in the viewDidLoad method. After this is done I update the tableview with tableView.reloadData().
override func viewDidLoad() {
super.viewDidLoad()
MYRequest_getUsers(//...
,
success: {response -> Void in
self.users = response
dispatch_async(dispatch_get_main_queue(),{
self.tableView.reloadData()
})
},
failure: {NSError -> Void in
debugPrint(NSError)
})
}
TableView counts the users and reloads itself.
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users?.count ?? 0
}
In tableView_cellForRowAtIndexPath method i fill the cells with user data.
let cell = tableView.dequeueReusableCellWithIdentifier(self.identifier) as! UserCell
cell.userNameLabel.tag = indexPath.row
let rowData: User = self.users?[cell.userNameLabel.tag] as User!
cell.userNameLabel.text = rowData.getName()
let avatarURL = rowData.getAvatarURL() ?? ""
cell.userImageView.af_setImageWithURL(imgURL, placeholderImage: placeholderImage)
return cell
My idea was that after user data was loaded, the tableView begin to draw itself and place the name (because it is already in userData). But the image is downloaded (i suppose) asynchronously, so that they come from the backend after some delay and tableView is already drawn. After scrolling up and down i see them.
I want to open the screen and without scrolling up and down. Tableview should set automatically the images after they were loaded. So i thought to make a callback and use instead of
cell.userImageView.af_setImageWithURL(imgURL, placeholderImage: placeholderImage)
this
Alamofire.request(.GET, avatarURL)
.responseImage { response in
cell.userImageView.image = response.2.value
dispatch_async(dispatch_get_main_queue(), { () -> Void in
tableView.setNeedsLayout()
})
}
But nothing changes... I've tried a lot and looked similar problems but can't solve it... I hope you can give me some hints or much better a solution! :)
Thanks in advance
I would like to give you a direction by posting the steps (best practice to follow in such case):
Step 1 : Fetch images in background as soon as you have image URLs available from server. I prefer doing this on operation queue where I download multiple images concurrently. You can write a helper class which takes a completion block and implement NSOperation/NSOperationQueue.
Step 2 : While images are being downloaded, for the eyes of users, put a loading overlay on image view. You can do this in cellForRowAtIndexPath:.
Step 3 : Once images are available, cache them in file system. This is to avoid any scrolling abrupt behaviour.
Step 4 : Once images are available, call the completion block.
Step 5 : In completion block, reload your table on main thread. Ensure your cellForRowAtIndexPath: first check the image in cache, if present use it, if not present show loading overlay if image fetch is on flight. If image is not available in cache and download is also not going on, show some default image.
This question is couple of years old, but maybe this answer can be useful to someone else with a similar problem, like me before to find the right solution.
Since the images are loaded asynchronously, we have to force a cell update when the download is finished if we didn't provide a fixed height for the UIIMageView. This because cell updating (i.e. AutoLayout Constraints recalculation) is done automatically only after cellForRowAt method, that is called when a cell is displayed for the first time, or when the table is scrolled to show other cells. In both cases probably the images are not yet downloaded by the af_setImage() method, so nothing but the placeholder will be displayed as their sizes are unknown for the moment.
To force a cell update we need to use beginUpdates() and endUpdates() methods, putting them inside the completion handler of .af_setImage(). This way, every time the downloading is completed, the cell will be updated.
But, to avoid a loop, before to call beginUpdates()/endUpdates() we have to check if we have already update the cell before, because by calling these methods, the cellForRowAt method is called again and consequently the af_setImage() and its completion closure with beginUpdates()/endUpdates() inside it).
This means that we have to update the cell only when the download is just finished, and not when the imaged is cashed (because, if it is cashed, it means that we have already updated the cell). This can be accomplished by checking the response of the completion handler: if it is not nil, the image was just downoladed, if it is nil, the image was cashed.
As a side benefit the cell height will be automagically adjusted (remember to put tableView.estimatedRowHeight = 400 and tableView.rowHeight = UITableViewAutomaticDimension in your viewDidLoad() method)
Finally, here it is the code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Dequeue your cell
let cell = self.tableView.dequeueReusableCell(withIdentifier: "YourCustomCellIdentifier") as! YourCustomTableViewCell
// get picture url from the data array
let pictureUrl = self.yourCellsData[indexPath.row].pictureUrl
// async download
cell.pictureView.af_setImage(
withURL: URL(string: pictureUrl)!,
placeholderImage: UIImage(named: "YourPlaceholder.png"),
filter: nil,
imageTransition: UIImageView.ImageTransition.crossDissolve(0.5),
runImageTransitionIfCached: false) {
// Completion closure
response in
if response.response != nil {
// Force the cell update
self.tableView.beginUpdates()
self.tableView.endUpdates()
}
}
return cell
}
That's all folks! ;-)
Few things to achieve this.
call data download in viewwillappear and not in viewdidload.
in viewdidload, hide the tableview.
in viewdidAppear: check the data has downloaded and if so then call
[tableview reloaddata] method.

Checkbox in UITableView change and revert images

I have a tableView with custom tableViewCell. Each cell has an image on the left (see screen 1). The custom tableViewCell has been subclassed. Every row has a different image which depends on indexPath.row
If I click on the image(s) the screen, the images should change to tick boxes so user can multiselect (see screen 2). If I click back on the image with a tick, it should revert back to old image on screen 1.
Issue :
I know how to change the image to tick mark but don't know how to go back to old image (pls remember every row has a different image - so the "else" part in my below code will not make sense).
Below is my code to change and revert the image
#IBAction func imageTap(sender: AnyObject) {
let imageView : UIImageView! = sender.view! as! UIImageView
if imageView.image != UIImage(named: "Oval 5"){
imageView.image = UIImage(named: "Oval 5")
awardBadge.hidden = false
}
else // Need to figure out how to go back to same image
{
imageView.image = UIImage(named: "Oval 1")
awardBadge.hidden = true
}
}
Add a boolean named "isTicked", or something like that, to your cell and set it to the right value at selecting / deselecting. Based on this value, you can set the right image. Let the cell do the rest.
Comparing images makes it unnecessarily complex and less performing.
You should track selected items. The easiest way would be to define an array of booleans in the view controller's subclass.
Define the delegate for you UITableViewCell's subclass like:
protocol MYCustomCellDelegate {
func didSelectedCell(cell: MYCustomCell)
}
And handle it in your controller:
func didSelectedCell(cell: MYCustomCell)
{
let indexPath = tableView.indexPath(cell: cell)
selectedItems[indexPath.row] = !selectedItems[indexPath.row]
tableView.reloadItemsAtIndexPaths([indexPath])
}
In the cellForItemAtIndexPath method set the state of you cell according to the selectedItems[indexPath.row]. If it is selected show the checkbox, if it is not - image:
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! MYCustomCell
cell.setTitle(titles[indexPath.row])
cell.setSelected(selectedItems[indexPath.row])
cell.delegate = self
return cell
}
i think you approach would be different, why don't you use the custom image button with 2 different images which represents selected and normal state. available states are normal/highlighted/selected/disabled. when we have custom image button, since you are using the static images, you would use your images for default state and tick image for selected state. all you have to do is just use the inbuilt property selected.

Resources