2013-03-03 32 views
0

如果图像不从url加载,我如何将本地image.png添加到单元格?如果UIImage没有从网址加载

- (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字符串数组。

回答

1

您可以通过检查图像来检查图像的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. 
          } 
}]; 
+0

仍然不会显示本地图像 – Asike 2013-03-03 11:45:36

+0

检查您在浏览器上使用的网址,并检查是否存在图像。你甚至可能会得到一个非常小的图像(比如尺寸为1px的方块),所以请确认在使用浏览器时。 – Shashank 2013-03-03 11:49:09

+0

谢谢!有用。我没有在代码中加入“其他” – Asike 2013-03-03 11:50:46