![](/img/trans.png)
[英]Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling?
[英]Downloading url image and uitableview cell image loading from local with parallel execution in iOS. how to implement?
我正在使用sqlite在iOS中存储图像本地路径。 我的过程如下...从服务器返回多个图像的url路径。 我将URL图像转换为数据(NSData)并将此数据写入本地路径(文档目录)。(此过程在后台线程中完成)。下一步是将本地路径(图像本地路径)保存到sqlite表中。 我的tableview单元格图像必须从我的本地路径图像(而不是url图像)加载。当我下载一个url图像并将图像路径保存到sqlite然后从本地路径加载我的单元格图像时,我需要这样。 我的代码如下
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
//Code here is executed asynchronously
for (int i=0; i<[insertedRowList count]; i++) {
Messages *mMsg = [insertedRowList objectAtIndex:i];
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString: mMsg.msgData]];
mMsg.msgLocalPath = [self saveImage:data withFileName:[self getCurrentDateTimeAsNSString] ofType:@"png" inDirectory:documentsDirectoryPath];
NSData * profData = [NSData dataWithContentsOfURL:[NSURL URLWithString: mMsg.profSerPath]];
mMsg.profLocPath = [self saveImage:profData withFileName:[self getCurrentDateTimeAsNSString] ofType:@"png" inDirectory:documentsDirectoryPath];
BOOL msgsuccess = NO;
msgsuccess = [[DataBaseManager getInstance]updatMsgImagePath: mMsg]; //save my image local path to sqlite table
if (msgsuccess == NO) {
}
}
});
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellId = @"myMessageCell";
MessageCell *cell = (MessageCell*)[tableView dequeueReusableCellWithIdentifier:cellId];
if (cell==nil) {
cell = [[MessageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
Messages *mMsg = [usersArray objectAtIndex:indexPath.row];
[cell.profImgView setImage:[UIImage imageNamed: mMsg.profLocPath]]; //this path is return from sqlite table.path is like users/……/documents/image.png
return cell;
}
我建议使用一个库进行后台下载和图像缓存,虽然那里有几个库,但是我喜欢SDWebImage ,如果设备中已经存在该库,它将使用缓存的版本。 另一个选择是AFNetworking 。
编辑:重新阅读您的问题,仍然不是100%清楚您需要什么。 据我所知,您正在下载映像并将其保存在设备中,然后将其路径保存在数据库中。 我不会将NSData和本地路径保存在数据库中,而是将远程路径直接保存在数据库中( mMsg.msgData
),并使用SDWebImage来负责将图像下载和缓存在磁盘中,您可以使用一些方法像这样
[cell.imageView setImageWithURL:[NSURL URLWithString:mMsg.msgData]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
或者可以使用保存在数据库中的任何路径来代替mMsg.msgData
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.