How to load images from JSON into UIImageView using SDWebImage?

ぃ、小莉子 提交于 2020-02-03 01:30:33

问题


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


来源:https://stackoverflow.com/questions/24984949/how-to-load-images-from-json-into-uiimageview-using-sdwebimage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!