簡體   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