【问题标题】:NSData with an error "The operation couldn’t be completed. (Cocoa error 256.)" [duplicate]NSData 出现错误“无法完成操作。(Cocoa 错误 256。)” [重复]
【发布时间】:2013-09-23 01:34:11
【问题描述】:

尝试显示从网络服务下载到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中显示图像。

【问题讨论】:

  • dataWithContentsOfURL 不适合远程图像加载 - 这是一个阻塞操作,当您发现您得到的错误处理和信息非常少时。您应该考虑使用NSURLRequest,或者使用许多开源UIImage 类别之一,这些类别可以直接从图像视图进行远程图像加载。
  • 使用 AsyncImageView 这是加载图片 url 的最佳方式

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


【解决方案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];

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

【讨论】:

  • 坦率地说,无论如何你都不应该使用dataWithContentsOfURL 通过网络加载远程数据。
  • 它会阻塞主 UI 线程,但我不确定他是否在偶数处理程序上执行此操作 :)
  • 即使您在完成处理程序上执行此操作也是错误的,因为您正在调用非线程安全的 UIKit 方法。 dataWithContentsOfURL 从未设计用于远程 URL 加载。使用像UIImageView+AFNetworking 这样的东西要好得多,它会为你处理所有事情并且给你很多错误处理。 NSData 方法的一大问题是在网络/下载失败的情况下它的反馈为零。
【解决方案2】:

使用 AsyncImageView 加载图片

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

https://github.com/nicklockwood/AsyncImageView

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2012-09-25
    相关资源
    最近更新 更多