我正在try 从URL获取图像,但它似乎对我不起作用.有人能给我指出正确的方向吗?

这是我的代码:

NSURL *url = [NSURL URLWithString:@"http://myurl/mypic.jpg"];

NSString *newIMAGE = [[NSString alloc] initWithContentsOfURL:url
                                       encoding:NSUTF8StringEncoding error:nil];

cell.image = [UIImage imageNamed:newIMAGE];

当我调试newIMAGE字符串时,它是nil,所以那里有些东西不工作.

推荐答案

您需要的是获取图像数据,然后使用该数据初始化UIImage:

NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: @"http://myurl/mypic.jpg"]];
cell.image = [UIImage imageWithData: imageData];
[imageData release];

根据要求,这里有一个异步版本:

dispatch_async(dispatch_get_global_queue(0,0), ^{
    NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: @"http://myurl/mypic.jpg"]];
    if ( data == nil )
        return;
    dispatch_async(dispatch_get_main_queue(), ^{
        // WARNING: is the cell still using the same data by this point??
        cell.image = [UIImage imageWithData: data];
    });
    [data release];
});

Objective-c相关问答推荐

Objective C 中的 RSA 实现

如何使用 UIStepper

UIApplication.sharedApplication.delegate.window 和 UIApplication.sharedApplication.keyWindow 有什么区别?

Asihttprequest 61 错误

带有 IB_DESIGNABLE 的 UIButton 会引发运行时属性警告,并且不会在 Interface Builder 中呈现

检测到与加载的库不匹配的 UUID

如何删除应用程序指定目录中的所有文件?

未找到 RKObjectMapping.h

UIFont 的磅值到底是多少?

属性与实例变量

何时应该使用 initWithNibName 初始化视图控制器?

从昨天开始无法将存档上传到应用store

NSManagedObjectContext:异常断点在 save: 方法处停止,但没有日志(log)/崩溃/错误

如何以编程方式移动 UIScrollView 以集中在键盘上方的控件中?

如何在 UIImageView 中显示 base64 图像?

UICollectionView 仅在用户双击时调用 didSelectItemAtIndexPath,当用户单击时不会调用

IOS 中的圆形进度条

-fembed-bitcode 在 6.0 之前的 iOS 版本上不受支持

即使在静音模式下也能在 iPhone 上播放声音

带有Go按钮而不是返回的 iOS 键盘