How do you update UITableViewController after download completes
-
21-12-2019 - |
سؤال
I have a tableViewController
, that when it loads a cell it calls another class, DownloadData
which is a UIOBject
, which initializes a bunch of data. That class calls a downloader which downloads a file. I don't want to wait for this file to be downloaded to initially load my table, but the table has fields for the downloaded data. I'd like to refresh my table when it's complete. The download, when complete, calls the method:
- (void) URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
which is in the DownloadData
class. What is the best way that I can make the above method, when called, force my table view to update? Thank you!
المحلول
We had a similar set up in our app. On a high level our cellForItemAtIndexPath
immediately would return a dummy "place-holder" cell, and kick off the download for the real cell. When we kicked off the download we would pass the cell to the downloader, and when the download completed it could just change replace the placeholder with the image itself (be sure to do this on the main thread).
It looks something like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UICustomCellWithImageView *cell = (UICustomCellWithImageView *)[collectionView dequeueReusableCellWithReuseIdentifier:YourCellID forIndexPath:indexPath];
[self.downloadManager downloadImageForCell:cell
completionBlock:^(){
[cell setPlaceholderHidden:YES animated:YES];
}];
return cell;
}
and on your downloader:
- (void)downloadImageForCell:(UICustomCellWithImageView *)cell (void(^)())completionBlock {
[self downloadImageWithCompletion:^(UIImage img) {
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = img;
if (completionBlock) {
completionBlock();
}
}
}
forgive any compiler errors, I just wrote up some example code in this window, as it turns out obj-c is a hard language to write without a compiler / auto-complete =). Ours is a little more complicated than this, as we don't know the size of the image before hand, and I don't think our downloader knows about our custom cell class, but I just wrote it as such for simplicity to get the concepts.
نصائح أخرى
[tableView reloadData]
? Or what exact problem do you have?