How to load images from JSON into UIImageView usin

2019-06-10 06:27发布

问题:

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


    }

回答1:

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



回答2:

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