如果在JSON对象中加载空图像URL,则应用程序崩溃

时间:2014-02-24 04:19:43

标签: ios json uitableview

我通过JSON使用MySQL表中的对象填充tableView。 源数据由许多用户以网站形式引入,有时他们不会将图像URL引入字段。

下载的JSON对象显示在tableView中,哪些行配置为显示文本,详细文本和图像。

如果对象没有图片网址,则应用程序崩溃,我想显示默认图片,以避免崩溃。

这就是我如何加载对象图像的JSON数据:

    NSMutableString *logo = [[NSMutableString alloc]initWithString:@"http://mujercanariasigloxxi.appgestion.eu/logos/"];
    NSString *imageURL = [[categorias objectAtIndex:indexPath.row] objectForKey:@"strImagen"];
    [logo appendString:imageURL];
    NSURL *logoURL = [NSURL URLWithString:logo];
    NSData *logoData = [NSData dataWithContentsOfURL:logoURL];


    cell.imageView.image = [UIImage imageWithData:logoData];

如果网站用户在网络表单中不包含图片网址,那么避免崩溃的最佳方法是什么,并显示默认图片?

3 个答案:

答案 0 :(得分:1)

尝试使用if-else条件,例如

NSMutableString *logo = [[NSMutableString alloc]initWithString:@"http://mujercanariasigloxxi.appgestion.eu/logos/"];

NSData *logoData;
if([categorias objectAtIndex:indexPath.row] && [[categorias objectAtIndex:indexPath.row] objectForKey:@"strImagen"]){
   NSString *imageURL = [[categorias objectAtIndex:indexPath.row] objectForKey:@"strImagen"];
   [logo appendString:imageURL];
   NSURL *logoURL = [NSURL URLWithString:logo];
  logoData = [NSData dataWithContentsOfURL:logoURL];
}
else {
   //load your default image here
   logoData = //default logo data
}


cell.imageView.image = [UIImage imageWithData:logoData];

答案 1 :(得分:1)

//set an activity indicator                 
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
    NSString *imageURL = [[categorias objectAtIndex:indexPath.row] objectForKey:@"strImagen"];
    if (imageURL.count>0){
        [logo appendString:imageURL];

        //declare logodata as nsdata
        logoData=[NSData dataWithContentsOfURL:[NSURL URLWithString:logo]];
    }

    dispatch_sync(dispatch_get_main_queue(), ^{

        //turn the activity indicator off
        if(logoData!=nil)
            cell.imageView.image = [UIImage imageWithData:logoData];
        else
            //set your default image.
            });
});

希望这对你有所帮助。

答案 2 :(得分:1)

您可以尝试检查imageurl是nil还是在某些情况下它会显示为null

NSMutableString *logo = [[NSMutableString alloc]initWithString:@"http://mujercanariasigloxxi.appgestion.eu/logos/"];
NSString *imageURL = [[categorias objectAtIndex:indexPath.row] objectForKey:@"strImagen"];


if(imageURL != nil && ![imageURL isEqual:[NSNull null]])
{
    [logo appendString:imageURL];
    NSURL *logoURL = [NSURL URLWithString:logo];
    NSData *logoData = [NSData dataWithContentsOfURL:logoURL];
    cell.imageView.image = [UIImage imageWithData:logoData];
}
else{
    cell.imageView.image = [UIImage imageNamed:@"Default_image"];
}