I have seen several posts on this here at SO but those solutions don’t seem to work for me. Perhaps it’s because I’m getting the image URL via JSON. All other text fields in JSON are coming through OK, it’s just the image that I can’t display and get a SIGABRT error.
The code in question is this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"PostCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *post = [posts objectAtIndex:indexPath.row];
NSString *postText = [post objectForKey:@"post_text"];
NSString *postAuthorName = [post objectForKey:@"post_author_name"];
NSString *postPictureUrl = [post objectForKey:@"post_picture"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:postPictureUrl]];
cell.textLabel.text = postText;
cell.detailTextLabel.text = [NSString stringWithFormat:@"by %@", postAuthorName];
cell.imageView.image = [UIImage imageWithData:data];
return cell;
}
My Table Cell is subtitle with no other changes or wiring.
Any idea where I’m messing up?
PS My full code using async request
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"PostCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *post = [posts objectAtIndex:indexPath.row];
NSString *postText = [post objectForKey:@"post_text"];
NSString *postAuthorName = [post objectForKey:@"post_author_name"];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *postpictureUrl = [post objectForKey:@"http://example.com/post/1200"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:postpictureUrl]];
// NSLog(@"%@", data);
dispatch_async(dispatch_get_main_queue(), ^{
// [[cell imageView] setImage:[UIImage imageWithData:data]];
});
});
cell.textLabel.text = postText;
cell.detailTextLabel.text = [NSString stringWithFormat:@"by %@", postAuthorName];
return cell;
}
A few minor changes and the below works (ie, thumbnail shows to the left of title and subtitle).
Note the use of
initWithStyle:UITableViewCellStyleSubtitleinstead ofDefault.The guide here is an important read:
http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/TableViewCells/TableViewCells.html
Finally, note this is synchronous downloading of images which will not work in the real world.
So I’ll be posting another question on SO about the best solution for this.