我编写了一个应用程序,它从 RSS feed 获取图像的 url 并将其显示在 UIImageView 中,我知道我正在提取的图像是有效的,因为图像的 url 直接转到我的标签,其中显示我输入了网址,然后它就转到了一张图片。这是一张jpg图像。令人烦恼的是,即使我手动输入图像的 URL,任何图像都不起作用。
这是我的代码, ImageView 代码位于底部。
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *URL = [NSURL URLWithString:@"http://rss.cnn.com/rss/edition_world.rss"];
NSData *data = [NSData dataWithContentsOfURL:URL];
// Assuming data is in UTF8.
NSString *string = [NSString stringWithUTF8String:[data bytes]];
titleLabelLatestNews.text = string;
NSString *webString = titleLabelLatestNews.text;
NSScanner *stringScanner = [NSScanner scannerWithString:webString];
NSString *content = [[NSString alloc] init];
while ([stringScanner isAtEnd] == NO) {
[stringScanner scanUpToString:@"url=\"" intoString:Nil];
[stringScanner scanUpToString:@"/>" intoString:&content];
NSString *filteredImage = [content stringByReplacingOccurrencesOfString:@"url=\"" withString:@""];
NSString *filteredImage2 = [filteredImage stringByReplacingOccurrencesOfString:@"\"" withString:@""];
titleLabelLatestNews.text = filteredImage2;
NSURL * imageURL = [NSURL URLWithString:filteredImage2];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * image = [UIImage imageWithData:imageData];
[imageView setImage:image];
}
我用于 imageView 的代码 -
NSURL * imageURL = [NSURL URLWithString:filteredImage2];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * image = [UIImage imageWithData:imageData];
[imageView setImage:image];
是不是因为JPG? 是因为我的ImageView吗? 一切都链接起来,一切都工作正常,除了这个我已经看到了所有关于如何从网址获取图像的帖子,我尝试了一切,但似乎没有任何效果, ImageView 保持空白和白色。
总结: 我正在从网站中提取图像链接,该链接是有效的,因为我测试了它,并且我尝试下载并放入 ImageView 中的任何其他图像也不起作用, ImageView 为空白,根本不显示任何内容。
感谢您的帮助!
最佳答案
好的,您看不到图像,因为 imageData 为 nil。 imageData 为 nil,因为 imageURL 也为 nil。
在创建 NSURL 之前需要对 url 字符串进行转义。
代替:
NSURL * imageURL = [NSURL URLWithString:filteredImage2];
做:
NSURL * imageURL = [NSURL URLWithString:[filteredImage2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
关于ios - 从 url 中提取的图像未出现在 UIImageView 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27519488/