我已成功接收到图像的 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/