0

如果图像未从 url 加载,我如何将本地 image.png 添加到单元格?

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";
    DetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    NSURL* url = [NSURL URLWithString:[arrayOfImages objectAtIndex:indexPath.row]];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse * response,
                                               NSData * imagedata,
                                               NSError * error) {
                               if (!error){
                                   UIImage* image = [[UIImage alloc] initWithData:imagedata];
                                   cell.flowerImage.image = image;
                               }                     
    }];

    return cell;
}

arrayOfImages- 我从 json 解析的 url 字符串数组。

4

1 回答 1

1

您可以对照 nil 检查图像以验证图像 url。

[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse * response,
                                           NSData * imagedata,
                                           NSError * error) {
                           if (!error){
                               UIImage* image = [[UIImage alloc] initWithData:imagedata];
                               if(!image) {
                                  cell.flowerImage.image = [UIImage imageNamed:@"localImage"]; //local bundle image.
                               } else
                                   cell.flowerImage.image = image;
                           } else {
                               cell.flowerImage.image = [UIImage imageNamed:@"localImage"];//local bundle image.
                           }
}];
于 2013-03-03T11:36:36.330 回答