我有 TableView、gallery 和其他项目。因此,当我打开我的应用程序时,我需要保存来自 JSON 的所有图像,并且当我在没有互联网的情况下打开应用程序时,我的图像必须显示。它是如何创建的?我必须做什么?我还有一部分代码用于将 tableViewCell 中的图像显示到 TableView:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
CellForNewsContent *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
CBAutoScrollLabel *captionLabel = [[CBAutoScrollLabel alloc] initWithFrame:CGRectMake(85, 10, 210, 20)];
UILabel *detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(85, 39, 220.0, 20.0)];
detailLabel.tag = 2;
captionLabel.tag = 1;
captionLabel.text = [_news[indexPath.row] valueForKey:@"title"];
captionLabel.scrollSpeed = 7;
[cell addSubview:captionLabel];
[cell addSubview:detailLabel];
UILabel *detailShow = (UILabel*)[cell viewWithTag:2];
detailShow.text = [[_news objectAtIndex:indexPath.row]objectForKey:@"date"];
[cell.imageView setImageWithURL:[NSURL URLWithString:[[_news objectAtIndex:indexPath.row] valueForKey:@"smallimg"]] placeholderImage:[UIImage imageNamed:@"noholder2@2x.png"]];
谢谢。
为图像添加了 JSON:
sliderurl : "http://site/m/miss/load/slider/3c01c445e13582c874bc56619ca47bb8.png"
1
sliderurl : "http://site/m/miss/load/slider/ba17268fa8d7d0f36fa35055960528fd.png"
2
sliderurl : "http://site/m/miss/load/slider/031b22e15228800b22105d4b97043681.png"
3
sliderurl : "http://site/m/miss/load/slider/bf484ddd41f02f8b762b517557760bfb.png"
4
sliderurl : "http://site/m/miss/load/slider/6718b988c4cf5cfb9f40219833d7118f.png"
5
sliderurl : "http://site/m/miss/load/slider/8593df80af29fe8014f9fc176991cb07.png"
6
sliderurl : "http://site/m/miss/load/slider/bf80cff0b085c63ff0416f7118659df6.png"
7
sliderurl : "http://site/m/miss/load/slider/45fbe8a52d174e145b3e98dbf9fa960c.png"
最佳答案
您想从 JSON 下载并缓存图像。我推荐使用 SDWebImage
.
您可以在获取 JSON 时开始异步下载所有图像,也可以在显示图像时延迟加载它们。后者意味着如果您的图片尚未被查看,则无法离线使用。
获取JSON后全部下载:
for (NSDictionary *item in _news) {
NSString *url = item[@"sliderurl"];
[SDWebImageDownloader.sharedDownloader downloadImageWithURL:url options:0 progress:nil completed:nil];
}
然后在您的 TableView 数据源方法中:
id url = _news[indexPath.row][@"sliderurl"];
如果 ([url isEqualTo:[NSNull null]]) {
//如果没有给出图像,则使用占位符图像
cell.imageView.image = [UIImage imageNamed:@"noholder2.png"];
} 别的 {
[cell.imageView setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"noholder2.png"]];
}
第一个代码片段将下载所有图像并将被缓存。然后图像将在单元格加载时再次尝试请求 - 如果图像已经下载,则使用缓存图像。
关于ios - 从 JSON 写入/读取图像以在 Xcode 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23032198/