带有错误的NSData“操作无法完成。(Cocoa error 256.)”

时间:2013-09-18 10:24:47

标签: ios objective-c error-handling uiimage nsdata

尝试将从网络服务下载的图片显示到UIImage,可以获得确切的图片路径(URLString)并显示在NSLog中。现在问题是imageData返回null值而不是要返回的值。

错误消息打印为:

  

无法完成操作。 (可可错误256。)

用于检索图像路径的代码如下所述,

    NSString *urlString = [result objectForKey:@"image"];
    NSLog(@"url image is %@ \n",urlString);

    NSData *imageData = [[NSData alloc] init];

    NSError* error = nil; 
    imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString] options:NSDataReadingUncached error:&error];

    if (error) 
    {
        NSLog(@"%@", [error localizedDescription]);
    } 
    else
    {
        NSLog(@"image data is %@ \n",imageData);   
        imageview.image = [UIImage imageWithData:imageData];
    }

要在UIImage中显示图像,需要做什么。

2 个答案:

答案 0 :(得分:1)

这部分错了:

if (error) 
{
    NSLog(@"%@", [error localizedDescription]);
}

else
NSLog(@"image data is %@ \n",imageData);   
imageview.image = [UIImage imageWithData:imageData];

它应该是:

if (error) 
{
    NSLog(@"%@", [error localizedDescription]);
}

else
{
    imageview.image = [UIImage imageWithData:imageData];
}

你也在分配NSData,然后用另一个覆盖该值,不要使用这一行:

NSData *imageData = [[NSData alloc] init];

分配/初始化对象然后销毁它是浪费时间和内存。

答案 1 :(得分:0)

使用AsyncImageView加载图像

 AsyncImageView *ImageView = [AsyncImageView alloc]init];
    ImageView.imageURL =[NSURL URLWithString:ImageURLStr];

https://github.com/nicklockwood/AsyncImageView