Search code examples
parse-platformuiimagensdata

Convert data to an UIImageView


I try to convert data from parse.com into my UIImageView.

for (PFObject *object in objects)
    {
        PFFile *file = [object objectForKey:@"imageData"];
        [file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
            [contentImageArray addObject: [UIImage imageWithData:data]];
        }];

    }

I load my data in a NSMutableArray, this still works, but then I want my data in an ImageView.

So my code:

cell.contentImage.image = [UIImage imageWithData:[contentImageArray objectAtIndex:(contentImageArray.count - indexPath.row - 1)]];

But it does not work, I just get an error message, please help!


Solution

  • First, you need to check the error and that the data isn't nil because this isn't safe:

    [file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
        [contentImageArray addObject: [UIImage imageWithData:data]];
    }];
    

    if parse has an issue returning the data your app will crash.

    Also, in that code you are already creating the image from the data, so you don't need to do it again:

    cell.contentImage.image = [contentImageArray objectAtIndex:(contentImageArray.count - indexPath.row - 1)];
    

    Finally, you're making assumptions about what index each image has in the array and you have very specific indexing logic. That's unlikely to work well / properly in the future, even if it does now. You load images in the background and put them into an array - you have no idea what order the images are going to load in... You should apply logic to deal with that. If you load the table when you don't have any images they you'll be trying to get the (0 - 0 - 1)'th image from the array, and that isn't going to exist.


    From your follow on comment:

    Populate your contentImageArray with instances of NSNull for each of the objects you have. When you iterate the objects, keep the index and then when the image is ready you can:

    [contentImageArray replaceObjectAtIndex:i withObject:[UIImage imageWithData:data]];
    

    and when you try to use the image, check if it's available yet:

    id image = [contentImageArray objectAtIndex:indexPath];
    
    cell.contentImage.image = ([image isKindOfClass:[UIImage class]] ? image : nil);