如何使用SDWebImage将图像从JSON加载到UIImageView中? [英] How to load images from JSON into UIImageView using SDWebImage?

查看:131
本文介绍了如何使用SDWebImage将图像从JSON加载到UIImageView中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用SDWebImage在UIImageView中(类似于Tinder)显示来自JSON URL的图像.我遇到的每个教程都只涉及下载单个图像URL(@"suchandsuch.png")或在表视图中显示图像(我不想这样做).

I'm trying to display images from a JSON url in an UIImageView, similar to Tinder, using SDWebImage. Every tutorial I've come across only deal with downloading either single image urls (@"suchandsuch.png"), or displaying the images inside of tableviews (which I do not want to do).

不确定我做错了什么.

我的示例代码:ViewController.m

My sample code: ViewController.m

-(void)viewDidLoad{

    [super viewDidLoad];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
   [manager GET:@"http://www.suchandsuch.com/api/sites" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.posts = (NSDictionary *) responseObject;
        self.post = self.posts[@"sites"];
       NSLog(@"JSON: %@", self.post);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       NSLog(@"Error: %@", error);
    }];


    NSData *data = [[NSData alloc] initWithContentsOfURL:
                              [NSURL URLWithString:@"http://www.suchandsuch.com/api/sites"]];


    NSError *error;
    NSDictionary *jsonDict = [NSJSONSerialization
                                JSONObjectWithData:data
                                options:kNilOptions
                                error:&error];

    NSString *logoString = [jsonDict objectForKey:@"logoURL"];

    NSURL *logoURL = [NSURL URLWithString:logoString];
    [self.myImage setImageWithURL:logoURL];


    }

推荐答案

我认为您已经将SDWebImage文件添加到了项目中,并且知道如何解析JSON,这就是您需要做的所有事情.将此行添加到视图控制器类的顶部-

I take it you have the SDWebImage files added to your project already and that you know how to parse the JSON, here's all you need to do. Add this line to the top of your view controller class -

#import "UIImageView+Webcache.h

在解析并检索了对象之后,该对象将包含所需的imageUrl,例如从JSON中提取的字典(dict)

After you've parsed and retrieved the object contains the imageUrl that you need, for example the dictionary (dict) extracted from the JSON

示例

    NSString *jsonImageUrlString = [dict objectForKey:@"imageUrl"];

    NSURL *imageURL = [NSURL URLWithString:jsonImageUrlString];

    [[SDImageCache sharedImageCache] removeImageForKey:imageURL fromDisk:YES];

    [self.profileImageView setImageWithURL:imageURL];

我希望这对您有帮助

编辑 您应该已经在项目中的 SDWebImage文件

EDIT SDWebImage files that you should already have in your project

这篇关于如何使用SDWebImage将图像从JSON加载到UIImageView中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆