文章目录
iOS实现列表上传/下载
场景
我们在进行文件上传或者下载的时候,经常使用到列表上传/下载,列表的每条显示各自的下载进度等。
实现思路
实现一个tableView,没上传一个文件,添加一个数据源,列表里添加一条cell。每个cell显示各自的上传进度情况,互不干扰。
实现思路一
//添加文件上传
- (void)addUploadFileWithPath:(NSString *)filePath
{
//生成数据模型
VHUploadModel *model = [[VHUploadModel alloc] init];
model.vodInfo = [[VHVodInfo alloc] init];
model.vodInfo.name = [filePath lastPathComponent];
model.vodInfo.desc = [NSString stringWithFormat:@"测试上传_iOS_%f",[[NSDate date] timeIntervalSince1970]];
model.filePath = filePath;
//向数据源中添加一个数据
[self.dataSource addObject:model];
//刷新tableView,添加一个cell(或者这里直接添加一个cell)
[self.tableView reloadData];
//调用上传
__weak typeof(self)weakSelf = self;
[self.uploder uploadFilePath:model.filePath vodInfo:model.vodInfo progress:^(VHUploadFileInfo * _Nonnull fileInfo, int64_t uploadedSize, int64_t totalSize) {
//因为所有文件的上传回调都从这里回调,所以在这里我们需要区分是哪一个文件的上传进度回调
NSInteger index = [weakSelf.dataSource indexOfObject:model];
//刷新数据源数据
model.progress = 1.f * uploadedSize / totalSize;
//初始化一个indexPath对象
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
//主线程刷新progress
dispatch_async(dispatch_get_main_queue(), ^{
//这里通过indexPath拿到对应的cell
VHUploadCell *cell = [weakSelf.tableView cellForRowAtIndexPath:indexPath];
//刷新cell上的数据
cell.progressView.progress = model.progress;
});
} success:^(VHUploadFileInfo * _Nonnull fileInfo) {
} failure:^(VHUploadFileInfo * _Nonnull fileInfo, NSError * _Nonnull error) {
}];
}
这样做不会出现滑动时tableView“卡”或“跳”的情况,刷新进度的时候我们只是做了两件事:1、修改了数据源,2、直接给cell的控件赋了新值。
不用担心因cell复用导致cell显示问题,因为tableView只刷新当前显示在界面上的cell的数据,当从第一页滑动到第二页,第二页复用第一页的cell,当滑动的时候同时也会重新刷新cell的显示,显示成第二页数据源的进度。
实现思路二
我看gitHub上有人写的Demo是给cell添加监听,监听上传进度,实现自身数据的刷新,应该也是可以实现。
要注意的一点就是,每个cell监听的都是所有的进度回调,所以需要判断是当前cell的进度再去刷新。