2013-03-03 29 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