Search code examples
iosasynchronousuitableviewuiimagereactive-cocoa

iOS Loading images in UITableViewCell with RAC


Am just starting with RAC and am wondering how to load images asynchronously in a cell within a TableView. I was trying with the example in the doc, but to be honest, I didn't understand so well... The thing is that the project is written with RAC, so I want to do the right things.

What have I tried?:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *CellIdentifier = @"tableCell";
  CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
  cell.elementName.text = self.myListOfElements[indexPath.row].elementName;
  RAC(cell.imageView, image) = [[finalImage map:^(NSURL *url) {
                                  return  [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.myListOfElements[indexPath.row].url]]];
                                    }] deliverOn:RACScheduler.mainThreadScheduler];
}

But this is not working... Does anybody know the proper way to do this with RAC?


Solution

  • I have never used RAC, but based on the examples it looks you are referencing a URL that you do not seem have.

    RAC(self.imageView, image) = 
    [
        [
            [
                [
                    client fetchUserWithUsername:@"joshaber"
                ]
                deliverOn:[RACScheduler scheduler]
            ]
            map:^(User *user) {
                // Download the avatar (this is done on a background queue).
                return [[NSImage alloc] initWithContentsOfURL:user.avatarURL];
            }
        ]
        // Now the assignment will be done on the main thread.
        deliverOn:RACScheduler.mainThreadScheduler
    ];
    

    In the example this section:

    [
        [
            client fetchUserWithUsername:@"joshaber"
        ]
        deliverOn:[RACScheduler scheduler]
    ]
    

    -fetchUserWithUsername is the function that returns the User object that contains the URL used to download the image.