ios - 使用 objectForKey 将 URL 从 JSON 转换为 UIImageView 的图像

标签 ios objective-c json asynchronous uiimageview

我已成功接收到图像的 URL,但我不知道如何将该 URL 转换为要在 ImageView 内部使用的实际图像。许多人建议首先异步加载图像。不幸的是,这就是他们要说的全部内容,没有进一步解释就让我离开。我的 JSON 在层次结构中设置,因此我使用键作为值。我应该在与字符串相同的 JSON 文件中发送图像 URL 吗?一般来说,JSON 是执行此操作的正确方法吗?感谢您的帮助。

    NSURL *myURL = [[NSURL alloc]initWithString:@"http://domain.com/json2.php"];
    NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];
    NSError *error;

    jsonArray = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:&error];

    [tableView reloadData]; // if tableView is unidentified make the tableView IBOutlet
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return jsonArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NeedCardTableViewCell *cell = (NeedCardTableViewCell *) [tableView dequeueReusableCellWithIdentifier:@"needCard" forIndexPath:indexPath];

    NSDictionary *needs = jsonArray[indexPath.row]; // get the data dict for the row
    cell.textNeedTitle.text = [needs objectForKey: @"needTitle"];
    cell.textNeedPoster.text = [needs objectForKey: @"needPoster"];
    cell.textNeedDescrip.text = [needs objectForKey: @"needDescrip"];

    return cell;

我需要将我的图像加载到名为“imageProfPic”的 UIImageView 中。

@interface NeedCardTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *textNeedTitle;
@property (weak, nonatomic) IBOutlet UILabel *textNeedPoster;
@property (weak, nonatomic) IBOutlet UILabel *textNeedDescrip;
@property (weak, nonatomic) IBOutlet UIImageView *imageProfPic;
@property (strong, nonatomic) IBOutlet UITableView *tableView;

最佳答案

最简单的方法是使用第三方库,如 SDWebImage .在自述文件中,您会找到适合您需要的示例,只需使用从 JSON 解析中存储的 URL。
如果您想自己做,可以使用 GCD :

 dispatch_async(dispatch_queue_create("imageQueue", NULL), ^{ 
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:needs[@"yourURLKey"]]];
    dispatch_async(dispatch_get_main_queue(), ^{
        [cell.imageProfPic setImage:image];
    });
});

这会在后台线程中下载图像,并在主线程(UI 线程)中设置它

关于ios - 使用 objectForKey 将 URL 从 JSON 转换为 UIImageView 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23070115/

相关文章:

ios - 使用自动布局和大小类调整 Uibutton 的大小

ios - 手动设置框架时,UIView subview 不显示

iPhone - 触发 APNS

ios - 协议(protocol)委托(delegate)方法在 ios 中无法正确调用

objective-c - 如何在 Objective-C 中使用最小值和最大值生成随机 float ?

javascript - 使用 ajax 调用进行 JSON 字符串化

AppStore 中应用程序的 iOS 共享扩展?

iPhone Tesseract 库错误

javascript - 当用户收到新消息时重新加载页面不起作用

json - d3 - "Cannot create property ' vx' 在号码 '65' 上”