我已成功收到图片的网址,但我无法将该网址转换为在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;
答案 0 :(得分:1)
最简单的方法是使用像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线程)
中答案 1 :(得分:0)
我建议使用像AFNetworking这样的框架,它附带一个类别来直接从URL加载图像。
[cell.imageProfPic setImageWithURL:url];
答案 2 :(得分:0)
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:yourImageURLString]];
UIImage *image = [UIImage imageWithData:imageData];