Legen Diary
Legen Diary

Reputation: 365

How to assign a UIimage while within a block

I'm making a request to a URL to download an image. I receive it as an NSData object, but when I try to convert it to a UIimage with imageWithData: the UIImage is not loaded. Here's my Code

__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
__weak typeof(request)weakRequest = request;
__block UIImage * imager;
__block NSData * image;
[request setCompletionBlock:^{
    [self parseXMLFileAtFileId:[weakRequest responseData]];
    if (!files){
        cell.correctImage.image = [UIImage imageNamed:@"sidebarPlaceholder"];
    }
    else{

        NSURL *url = [NSURL URLWithString:[self downloading:[files objectAtIndex:0]]];
        __block ASIHTTPRequest *requester = [ASIHTTPRequest requestWithURL:url];

        __weak typeof(request)weakRequesting = requester;
        [requester setCompletionBlock:^{
            image =  [weakRequesting responseData];
            imager = [UIImage imageWithData:image];
            cell.correctImage.image = imager;
            [cell layoutIfNeeded];
        }];

        [requester startAsynchronous];
    }
}];

Previously I got it working by explicitly stating the size of the UIImageView, but that should be taken care of by the UITableviewCell. How do I get the image to show up?

Upvotes: 1

Views: 206

Answers (1)

ldindu
ldindu

Reputation: 4380

Try to run these block of code in main thread as it appeared you are trying to set the image and updating layout in background thread. Use following NSThread method right after

UIImage *imager = [UIImage imageWithData:image]

[self performSelectorOnMainThread:@selector(updateImage:) withObject:imager waitUntilDone:false];

// Define method to update the image

- (void)updateImage: (UIImage *)paramImage {
    cell.correctImage.image = paramImage;
    [cell layoutIfNeeded];
}

Upvotes: 1

Related Questions