Cancel NSOperations based on position in TableView/CollectionVIew - ios

Suppose I have a table view or a collection view. In the cells I would need to load certain content (eg. an Image). I can get the content from local storage (if it has been saved there) or from the internet. Either way loading the content takes a while (500 kB Image).
The best way to do this is to create an NSOperation that will load in the background and then call a delegate when it finishes.
But suppose the user enters the table view / collection view and the queues start to get the first set of content (1-10) but then the user scroll quickly right to the end (visible cells 100-110) what should I do? The start-download operation happens when the cell is presented (cellForRowAtIndexPath) so I need to wait for everything to download until the user (who is now at the end of the tableView) sees content.
I tried creating a queue on each cell and cancelling that in prepareForReuse, but that crashes the app.
Anyway if the user is in a section of the tableview and content is downloading, but not shown yet, and scrolls further causing the download to be cancelled and then returns. Then he will need to download the first half of the image again, which is not good on limited data plans.
What is the best way to handle such a situation?

You could have your controller class adopt the UITableViewDelegate protocol, which will allow you to inject custom code into –tableView:willDisplayCell:forRowAtIndexPath: (called for you by the table view when a cell is to be displayed). In it you could calculate that because of the screen size, only rows within k indices of any row being shown could possibly be visible; thus, in this method call, cancel all the load operations associated with rows outside that range (relative to indexPath argument).

Related

swift segue new viewcontroller stuck when other tasks loading on background

Currently, I have a UItableview which loads based on API. And when clicking on a cell, it segue(show e.g.push) to another viewcontroller. It displays all the cells after the first API call, then it calls other APIs and loads other data(which takes a while and also uses cpu heavily), but the scrolling seems to be smooth when loading.
However, when not fully loaded, if I click on a cell and the other viewController pops up, the entire app freezes for a moment. (The new viewController has all the content displayed, just not responsive)
Is there a solution for this?
What I can think of right now is to decrease the CPU load by loading fewer cells at a time.
Typically you are not going to want to do this:
"loads other data(which takes a while and also uses cpu heavily)"
The better solution would be to not call your second call to fetch all the data and just fetch the data needed to show on your next view controller you are segueing to. Typically done by passing an ID in your API call. So on your tableviews didSelectRowAt you would make the api call to get your data needed that is specific to the next screen, then segue.
If this is not possible due to server side limitations, then you are going to want to chain your first two calls. Meaning don't even show the table view cells until you have all the data.

Animate progress on 100s of UIButtons without blocking main thread

I have a UITableView with at most a few hundred cells (not all visible at once). Each cell contains a UIButton with a way to indicate progress of an upload. A URLSession performs the uploads in background tasks.
Currently, the session delegate is the UIViewController that manages the cells. As a result, the session calls delegate
.URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend: to periodically inform the delegate of the progress of sending content to the server.
In the delegate method, I find the UIButton associated with this task and animate the new progress (I can find the button because I make button.identifier = task.identifier).
This approach forces me to find the button every time the delegate method is called. This seems indirect and I am wondering if there is a better way to do this — there could be 100s of buttons so worried about runtime.
I was thinking to make the button be the session delegate, but that goes against MVC and the button reference may disappear or change in a table view causing undefined behavior (though it sort of makes sense to only update buttons that are actually in memory).
there could be 100s of buttons
No, there couldn't. Cells that do not appear on the screen do not exist at all (because cells are reused in a table view). So you only need to worry about the cells that are actually visible at any one moment. See UITableView visibleCells and indexPathsForVisibleRows. Thus, even though your approach is not extremely efficient, it isn't extremely inefficient either.
However, the correct way to do this is to use the progress object vended by your upload task. When the upload starts, tell the cell or the button or whatever to start observing the progress object's fractionCompleted using key-value observing. Now the cell or the button or whatever is in direct contact with that one task and can update itself every time it hears that the fractionCompleted has changed. When the cell stops being displayed, stop observing. There's a little more to it (i.e. to cope with reused cells that scroll onto the screen when the corresponding task is already in progress) but that's the basic architecture you want.

Load all table view cell images all together in iOS

I want to load all table view cell images all together instead of waiting for scroll down. The images are loading from server. I can load all the images as data and store them in an array and show them. But is there any other way for this? Any kind of help would be really appreciated.
You could fetch the images asynchronously in the viewDidLoad method, that way the user does not have to wait and can immediately start interacting with the UI. As long as the images haven't loaded (i.e. images array size is 0) you could show a generic image. Once you are done fetching you can update the tableview by calling the reloadData method:
For efficiency, the table view redisplays only those rows that are visible
As the user starts scrolling in the tableview, any subsequent loaded cells will now be able to access the populated images array in the cellForRowAtIndexPath method.

What is a better way to deal with data after an async call using NSURLConnection?

This is the current logic that I'm using to populate a table view with NSURLConnection. It doesn't seem elegant to me.
Table View Controller's viewDidLoad method calls "sendConnection" method in my api wrapper class with the URL string as a parameter. This method makes the NSURLConnection. In connectionDidFinishLoading (which is in my wrapper class), another method is called (also in the wrapper class) with the connection as a parameter. This method extracts the URL from the connection object and examines it. It then uses a switch statement to deal with the data depending on the URL. The data is stored in variables in the wrapper class itself. By the time cellForRowAtIndexPath is called, the async call has finished and the data has been processed.
Is there a better way of doing this?
My reason for asking this is as follows:
I want to refresh a cell with a new height and a new text label when it is clicked. The data for this text label will be retrieved from the server upon the cell being tapped. Each cell will have slightly different data in the label (each cell represents a 'user' and the label will display how many mutual friends you have with the user). I want to store the data in the cell itself when the data is retrieved and then place it into the text label. This doesn't seem possible with my current way of making URL calls.
Any help with how to achieve this would be appreciated.
Here is some pseudo code for a pattern I like to use in these situations. Maybe it will help you as well.
- (void)viewDidLoad {
//1. put up some type of progressHud or spinner
//2. call your NSURL wrapper
//3. in the completion block of your wrapper, set your datasource variables
//example: #property (nonatomic,strong) NSArray *listOfData;
//4. create a custom setter for your datasource that calls tableview reload
//5. enable a refresh function; like "pull to refresh" or a bar button
//6. when pull to refresh is tapped or called, just repeat these steps
}
- (void)setListOfData:(NSArray*)listOfData {
_listOfData = listOfData;
if (_listOfData) {
[self.tableView reloadData];
}
}
As I read your question again, here are a couple more thoughts:
the pattern above will work for your initial load, to create the list of people or friends, etc.
If you plan on making another round trip after the cell is tapped, then you have to consider a number of issues. This is similar to a common problem with lazy loading images into tableview cells. There are issues like scrolling to consider - what if the cell is scrolled off the view before the data returns, for example, what if the cell has been reused, now the data is not tied to that cell any longer.
There are many async image libraries available on Github that would be good to look at to see how they solved those issues. Generally they are keeping track of the item in the cell and then checking if the cell is still in view and if so, they set the image.
You have a similar issue to solve. Tap the cell, get the new data, then update the cell. Resizing the cell will require you to reload it.
Look into [tableview reloadRowsAtIndexPaths:(NSArray*) with RowAnimation:(UITableViewRowAnimation)];
hope that helps
best wishes;
You should have a "Data Model" which represents the content (that is the cells) of your Table View.
Since you have "rows" in your table view, it makes sense this data model is a kind of array (possibly a NSArray) whose elements keep the data and state of the cell.
The data for each cell should not only have all the "data" properties rendered in your cell (e.g. the label) but also its state:
When a user tabs on a cell it will start an asynchronous task. This task may take a while to finish since it fetches data from a remote server. Think of several seconds, or even longer. You need to keep track of pending update tasks, since your implementation should prevent the user to update a cell again before the corresponding pending update task has been finished.
There are several techniques to accomplish this. One way is to have a property in your "Cell Data" class which reflects this state, for example:
#interface CellModel : NSObject
#property (atomic) BOOL hasPendingUpdate;
...
When the cell will be rendered, you retrieve the value of the property and render the cell appropriately.
When the update task finishes, it updates its cell model data.
This model update will eventually update your Table View. There are several techniques to accomplish this. You should take care about thread-safety here and the "synchronization" of your Data Model and the table view cells. For example ensure the value of the hasPendingUpdate only changes on the main thread - since otherwise your rendered cell may become out of sync with the data model (not to mention race conditions in case you modify and access the property on different threads without synchronization primitives).
While the cell waits for an update, it should visually indicate this state (using a spinner for example) and disable the action to start an update task.
Very much recommended is a "Cancel" button, which either cancels a certain cell update task or all pending update tasks.
When the user moves away from this view, you may consider to cancel all pending tasks.

How can I make my UITableView request the X next cells that are outside the visible table?

I would like to have my UITableView load 3 or 4 cells outside of the table so that any data to be shown there is already loaded when I scroll down.
I have some images, and data that must be downloaded before it can be shown in the cell.
This causes a visible delay before the images are loaded when scrolling.
I can manually trigger loading of this data by doing it in the UITableViewDataSource tableView:cellForRowAtIndexPath: method. I've done this before, but I'm curious if there's an easier way to do it.
Is there any way to expand the reusable cell pool, or adjust how the cells are loaded/recycled?
EDIT:
To clarify, I have lazy loading of images and data in place.
Everything works fine, I just wanted an easy solution to the "prefetching" problem.
Which can be solved in many ways that has nothing to do with the view itself. Right now you can easily see the images load as you scroll. I just wanted them to load right before they become visible.
You may be looking for an asynchronous table view that loads the data asynchronously.
Apple provides a sample app demonstrating this:
LazyTableImages
Of course, you could pre-cache the data and begin downloading data into your datasource before they scroll.
The general idea is that you are loading data into a datasource (that is separate from the UI), so you can do this at any time (and in the background). You can display temporary data or some type of loading image or spinner if the data isn't loaded yet.
If data of the cell will be loaded when cel becomes visible, you can programmatically scroll the table view by scrolling to the bottom cell and go back to the first cell without animation. Another way would be creating all the cells and placing them into array when your view controller is created, and feed the table from that array that contains already created cells. I think there is no way to extend the cell pool as you are asking. Hope this helps, Good Luck!

Resources