如何处理未下载的图像

时间:2013-06-12 18:31:28

标签: ios nsdata

我想处理下载线程无法从URL下载图像的情况,以下代码似乎不符合我的目的:

dispatch_queue_t DownloadQueue = dispatch_queue_create("Download Pic", NULL);
dispatch_async(DownloadQueue, ^{
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:detailImageURL]];
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([imageData isKindOfClass:[NSNull class]]) {
            detailImageView.image = [UIImage imageNamed:@"no_image_available.jpg"];

        }
        else{
            UIImage *image = [UIImage imageWithData:imageData];
            detailImageView.image = image;
        }
    });
});
dispatch_release(DownloadQueue);

1 个答案:

答案 0 :(得分:0)

@ Rob,thanx,解决方法解决了这个问题:

dispatch_queue_t DownloadQueue = dispatch_queue_create("Download Pic", NULL);
dispatch_async(DownloadQueue, ^{
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:detailImageURL]];
    if (imageData == nil) {
        detailImageView.image = [UIImage imageNamed:@"no_image_available.jpg"];

    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImage *image = [UIImage imageWithData:imageData];
            detailImageView.image = image;
    });
    }
});
dispatch_release(DownloadQueue);

在进入async区块之前,请先测试NSData是否为零。