简体   繁体   中英

How to load images from JSON into UIImageView using SDWebImage?

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).

Not sure what I am doing wrong.

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];


    }

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

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

Example

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

    NSURL *imageURL = [NSURL URLWithString:jsonImageUrlString];

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

    [self.profileImageView setImageWithURL:imageURL];

I hope this helps

EDIT SDWebImage files that you should already have in your project

在此处输入图片说明

Assuming you have a JSON structure which has a dictionary of imageUrl's . You need to convert the JSON to an NSObject through this snippet of code.

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"]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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