我正在使用 NSXMLParser 从提要中获取新的 RSS 故事,并将它们显示在 UITableView 中。但是现在我只想拍摄图像,并将它们显示在 UIScrollView/UIImageView 中(并排显示 3 张图像)。我完全迷路了。我正在使用以下代码从 URL 获取 1 张图像。
NSURL *theUrl1=[NSURL URLWithString:@"http://farm3.static.flickr.com/2586/4072164719_0fa5695f59.jpg"];
JImage *photoImage1=[[JImage alloc] init];
[photoImage1 setContentMode:UIViewContentModeScaleAspectFill];
[photoImage1 setFrame:CGRectMake(0, 0, 320, 170)];
[photoImage1 initWithImageAtURL:theUrl1];
[imageView1 addSubview:photoImage1];
[photoImage1 release];
这就是我完成的所有工作,并且对一张图片有效,而且我必须指定确切的 URL。你会建议我做什么来完成这个?
最佳答案
除了我的其他答案,它使用了一些辅助类并且有点假设您正在使用 Core Data 存储内容,这是一种纯粹的 NSXMLParser 方法。
在此示例中,我假设您设置了三个带有标签 (100,101,102) 的 UIImageView,以便我们可以访问它们。首先,启动解析器的代码:
// Set the URL with the images, and escape it for creating NSURL
NSString *rssURLString = @"http://feeds.gettyimages.com/channels/RecentEditorialEntertainment.rss";
NSString *escapedURL = [rssURLString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *rssURL = [NSURL URLWithString:escapedURL];
// rssParser is an NSXMLParser instance variable
if (rssParser) [rssParser release];
rssParser = [[NSXMLParser alloc] initWithContentsOfURL:rssURL];
[rssParser setDelegate:self];
success = [rssParser parse]; // return value not used
此时解析开始,NSXMLParser 将触发对其委托(delegate)方法的调用,因为它在 XML 中找到不同的开始和结束元素。
在这个例子中我只写了didStartElement
方法:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
// look for an attribute called url
if ([attributeDict objectForKey:@"url"]) {
currentString = [attributeDict objectForKey:@"url"];
NSLog(@"Image URL: %@", currentString);
NSString* escapedURL = [currentString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:escapedURL]]];
UIImageView * tmpImageView = (UIImageView*)[scrollView viewWithTag:100+imageCount];
[tmpImageView setImage:image];
NSLog(@"images found: %d", imageCount);
imageCount++;
if (imageCount>2) [rssParser abortParsing];
}
}
这里我们查看 attributeDict(NSDictionary 对象)是否包含 url 属性。如果是这样,我们将它抓取到 currentString 中,然后将其转义,以防万一它具有 NSURL 会拒绝的字符。然后我们从该 URL 创建一个图像,并根据标签号设置适当的 UIImageView 图像。 imageCount 是一个计数器;一旦我们完成了三个图像,我们就会告诉 NSXMLParser 中止解析 XML。
如果您的 XML 将 URL 放在元素标记内,例如:
<image>http://example.com/image.jpg</image>
您需要对 didEndElement
和 foundCharacters
做更多的工作。看相当优秀Introduction to Event-Driven XML Programming Guide for Cocoa .
我拼凑了一个快速而肮脏的应用程序来演示这个,你可以捕获它 here .
关于iPhone 开发 : Get images from RSS feed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2473323/