ios - 从本地下载 url 图像和 uitableview 单元格图像并在 iOS 中并行执行。如何实现?

标签 ios objective-c iphone xcode uitableview

我正在使用 sqlite 在 iOS 中存储图像本地路径。我的程序如下…… 从服务器返回多个图像的 url 路径。我将 url 图像转换为数据(NSData)并将此数据写入我的本地路径(文档目录)。(此过程在后台线程中完成)。下一步是将我的本地路径(图像本地路径)保存到 sqlite 表。我的 tableview 单元格图像必须从我的本地路径图像(不是 url 图像)加载。当一个 url 图像下载并将图像路径保存到 sqlite 然后从本地路径加载我的单元格图像时,我需要这样。如何在iOS中实现这个过程?我的代码如下

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,您可以使用您保存在数据库中的任何路径。

关于ios - 从本地下载 url 图像和 uitableview 单元格图像并在 iOS 中并行执行。如何实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27405148/

相关文章:

iOS - 以编程方式拒绝联系人权限(在用户接受后)

objective-c - 如何遍历 objective-c 中的 NSString?

objective-c - 如何从字体文件中获取字体名称?

ios - 向下滚动然后向上滚动后 UITableView 单元格消失

python - 使用 iPhone 加速度计数据获取图像的俯 View

iphone - 为什么我在启动 iPhone OS 应用程序时得到 "security policy error"?

ios - 显示状态栏和提示通知下拉

objective-c - 以编程方式创建布局约束

ios - 与 NSString 转换后 NSDate 不相等

iphone - 如何整合我的 Xcode 项目文件?