繁体   English   中英

如何使用SDWebImage将图像从JSON加载到UIImageView中?

[英]How to load images from JSON into UIImageView using SDWebImage?

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

不知道我在做什么错。

我的示例代码: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,这就是您需要做的所有事情。 将此行添加到视图控制器类的顶部-

#import "UIImageView+Webcache.h

解析和检索后,对象包含所需的imageUrl,例如从JSON中提取的字典(dict)

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

    NSURL *imageURL = [NSURL URLWithString:jsonImageUrlString];

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

    [self.profileImageView setImageWithURL:imageURL];

我希望这有帮助

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

在此处输入图片说明

假设您有一个JSON结构,其中包含imageUrl的字典。 您需要通过此代码片段将JSON转换为NSObject。

NSError *error;
NSDictionary*jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData    options:kNilOptions error:&error];

NSString *imageUrl = [jsonDictionary objectForKey:@"imageURLKEY"];

[yourImageView sd_setImageWithURL:[NSURL URLWithString: imageUrl] placeholderImage:[UIImage imageNamed:@"anyTempImage.png"]];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM