简体   繁体   English

在手机的UIImageView上从服务器加载图像

[英]Load image from server on a UIImageView in phone

I'm having a problem loading a remote image into a UIImageVIew... It just doesn't show the image, may be i'm missing something... 我在将远程图像加载到UIImageVIew时遇到问题...它只是不显示图像,可能是我丢失了某些东西...

I also use the described here but with the same results How to load image from remote server on the UIImageView in iphone? 我也使用此处描述的方法,但结果相同。 如何在iPhone的UIImageView上从远程服务器加载图像?

Can someone help me? 有人能帮我吗?

This is the code i'm using 这是我正在使用的代码

Im getting the data from a xml and on the image element I have the full path 我从xml获取数据,并且在图像元素上我有完整的路径

[[detailViewController detailImage] setImage:[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: [NSString stringWithFormat:@"%@", [[promoList objectAtIndex: promoIndex] objectForKey: @"image"]] ]]] ];

With this code the image are displayed correctly 使用此代码,图像可以正确显示

[[detailViewController detailImage] setImage:[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: @"http://localhost/promos/preview/1.jpeg"]] ]];

Since the bottom example works as expected and besides the url string the example looks the same the problem should be with getting the url string. 由于底部的示例按预期方式工作,并且除了url字符串外,该示例看起来相同,因此问题出在获取url字符串上。 The problem is also that the code looks the same but it is quite hard to see. 问题还在于代码看起来相同,但是很难看到。 I would refactor the code to something like: 我将代码重构为:

NSObject *urlObject = [[promoList objectAtIndex:promoIndex] objectForKey:@"image"];
NSString *urlString = [NSString stringWithFormat:@"%@", urlObject];
NSURL *url = [NSURL URLWithString:urlString];
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:imageData];

[[detailViewController detailImage] setImage:image];

Then you can debug the statement properly and make sure that you get what you expect after each step. 然后,您可以正确调试该语句,并确保在每个步骤之后都能得到期望的结果。

Update 更新资料

To remove newline and tabs you can: 要删除换行符和标签,您可以:

NSString *urlString = [NSString stringWithFormat:@"%@", urlObject];
urlString = [urlString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

If urlObject already is a string, which it should be, then you can do: 如果urlObject已经是一个字符串,应该是,那么您可以执行以下操作:

NSString *urlString = [urlObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

which would make it a bit cleaner. 这将使其更清洁。

UIImage *img = [[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString:@"http://...."]]] retain];
if (img != nil) 
{ 
    [imageViewName setImage:img];
    [img release]; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM