I've got an image's URL successfully being received, but I have no clue to convert that URL into an actual image to be used inside of an ImageView. Many have suggested asynchronously loading the image first. Unfortunately, that's all they have to say, and leave me without further explanation. My JSON is setup in a hierarchy, so I'm using keys for the values. Should I be sending the image URL in the same JSON file as the strings? Is JSON the correct way to do this in general? Any help is appreciated.

    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;

I'd need my image to load in the UIImageView titled "imageProfPic".

@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;
有帮助吗?

解决方案

The easiest way is to use a third party library like SDWebImage. In the readme you'll find a sample that fits your needs, just use the URL stored from the JSON parsing.
If you want to do it by yourself you can use 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];
    });
});

This downloads the image in a background thread, and sets it in the main thread (UI thread)

其他提示

I would recommend using a framework like AFNetworking which comes with a category to directly load images from a URL.

    [cell.imageProfPic setImageWithURL:url];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:yourImageURLString]];
UIImage *image = [UIImage imageWithData:imageData];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top