iphone - Xcode iPhone编程: Loading a jpg into a UIImageView from URL

标签 iphone objective-c xcode url uiimageview

我的应用程序必须从 http 服务器加载图像并将其显示到 UIImageView
我该怎么做?
我试过这个:

NSString *temp = [NSString alloc];
[temp stringwithString:@"http://192.168.1.2x0/pic/LC.jpg"]
temp=[(NSString *)CFURLCreateStringByAddingPercentEscapes(
    nil,
    (CFStringRef)temp,                     
    NULL,
    NULL,
    kCFStringEncodingUTF8)
autorelease];


NSData *dato = [NSData alloc];
 dato=[NSData dataWithContentsOfURL:[NSURL URLWithString:temp]];
 pic = [pic initWithImage:[UIImage imageWithData:dato]];

此代码在 View 的 viewdidload 中,但没有显示任何内容! 服务器正在运行,因为我可以从中加载 xml 文件。但我无法显示该图像!
我需要以编程方式加载图像,因为它必须根据传递的参数进行更改! 先感谢您。 安东尼奥

最佳答案

应该是:

NSURL * imageURL = [NSURL URLWithString:@"http://192.168.1.2x0/pic/LC.jpg"];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * image = [UIImage imageWithData:imageData];

一旦你有了 image 变量,你就可以通过它的 image 属性将它放入 UIImageView 中,即:

myImageView.image = image;
//OR
[myImageView setImage:image];

如果您需要转义原始字符串中的特殊字符,您可以这样做:

NSString * urlString = [@"http://192.168.1.2x0/pic/LC.jpg" stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL * imageURL = [NSURL URLWithString:urlString];
....

如果您以编程方式创建UIImageView,您可以:

UIImageView * myImageView = [[UIImageView alloc] initWithImage:image];
[someOtherView addSubview:myImageView];
[myImageView release];

关于iphone - Xcode iPhone编程: Loading a jpg into a UIImageView from URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2510223/

相关文章:

ios - UITabBarController 应用程序和pushViewController 失败

ios - 如何创建 list 用户体验体验?

swift - 在 swift 4 中单击导航 Controller 上的后退导航项时,是否有一种简单的注销方法?

iphone - 使用 UIRequiredDeviceCapabilities Corona SDK 将应用程序提交到 App Store 时出错

ios - 3x3 按钮的多点触控

iphone - Objective-C 中的特定类类型参数

ios - 如何打开包含UIview或图像的弹出窗口

iphone - 如何在 didSelectRowAtIndexPath : method 中找到部分

iphone - 是否可以有多个 iAd 实例?

iphone - 使 UICollectionView 中的 insertItemsAtIndexPath 不设置动画