objective-c - 如何显示来自 RSS 源的图像

标签 objective-c ios nsdictionary nsxmlparser

我正在尝试构建一个应用程序来显示来自 http://news.yahoo.com/rss/ 的最新 RSS 提要。 我能够使用 NSXMLParserDelegate 解析 xml,我能够显示日期和时间以及特定提要的标题,但我也想为每个提要显示图像,我知道如何解析主要元素但我不知道如何传递以 url 作为键的子元素的属性...例如上述提要包含以下内容:

<item>
  <title>fooo</title>
  <description ahref="some link" image src="http://l1.yimg.com/bt/api/res/1.2/Wo3_apH.kz7DMvOj7MDtRQ--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9ODU7dz0xMzA-/http://media.zenfs.com/en_us/News/ap_webfeeds/20c464ff99815420210f6a706700a792.jpg"
     </description>

我的表格 View 中需要来自 IMG SRC 的图像以及该特定提要的标题和日期。我对如何解析 IMG SRC 属性并将其添加到更改大小的表格 View 中感到困惑,这样它就不会破坏我的标题和日期。

到目前为止我所做的事情:

viewDidAppear

-(void)viewDidAppear:(BOOL)animated
 {
     if ([stories count] == 0) 
     {
         NSString * path = @"http://news.yahoo.com/rss/";
         [self parseXMLFileAtURL:path];
     }
     cellSize = CGSizeMake([newsTable bounds].size.width, 80);
 }

-(void)parseXMLFileAtURL:(NSString *)URL

- (void)parseXMLFileAtURL:(NSString *)URL
{
    stories = [[NSMutableArray alloc] init];

    //you must then convert the path to a proper NSURL or it won't work
    NSURL *xmlURL = [NSURL URLWithString:URL];

    // here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
    // this may be necessary only for the toolchain
    rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];

    // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
    [rssParser setDelegate:self];

    // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
    [rssParser setShouldProcessNamespaces:NO];
    [rssParser setShouldReportNamespacePrefixes:NO];
    [rssParser setShouldResolveExternalEntities:NO];
    [rssParser parse];
}

didStartElement

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    //NSLog(@"found this element: %@", elementName);
    currentElement = [elementName copy];

    if ([elementName isEqualToString:@"item"]) {
        // clear out our story item caches...
        item = [[NSMutableDictionary alloc] init];
        currentTitle = [[NSMutableString alloc] init];
        currentDate = [[NSMutableString alloc] init];
        currentSummary = [[NSMutableString alloc] init];
        currentLink = [[NSMutableString alloc] init];
    }
}

发现字符

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    //NSLog(@"found characters: %@", string);
    // save the characters for the current item...
    if ([currentElement isEqualToString:@"title"]) {
        [currentTitle appendString:string];
    } else if ([currentElement isEqualToString:@"link"]) {
        [currentLink appendString:string];
    } else if ([currentElement isEqualToString:@"description"]) {
        [currentSummary appendString:string];
    } else if ([currentElement isEqualToString:@"pubDate"]) {
        [currentDate appendString:string];
    }
}

didEndElement

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    //NSLog(@"ended element: %@", elementName);
    if ([elementName isEqualToString:@"item"]) {
        // save values to an item, then store that item into the array...
        [item setObject:currentTitle forKey:@"title"];
        [item setObject:currentLink forKey:@"link"];
        [item setObject:currentSummary forKey:@"summary"];
        [item setObject:currentDate forKey:@"pubDate"];
    }
}

didEndDocument

- (void)parserDidEndDocument:(NSXMLParser *)parser 
{
    [newsTable reloadData];
}

numberOfRows 和 cellForRowAtIndexPath

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [stories count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
         cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier] autorelease];
    }

    int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
    cell.textLabel.text=[[stories objectAtIndex: storyIndex] objectForKey: @"title"];
    cell.detailTextLabel.text=[[stories objectAtIndex:storyIndex] objectForKey:@"pubDate"];

    cell.textLabel.font=[UIFont fontWithName:@"Arial" size:12];
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;

    return cell;
}

如何获取单元格右侧的图像?

最佳答案

为了回答标题中的问题,要加载图像,您可以使用 NSXMLParser 解析 RSS 提要以获取字符串的 URL。对象,当您想要向用户呈现该图像时,您可以使用该 URL 将图像检索到 NSData 中。 ,创建一个UIImage为此,然后设置 image UIImageView的属性(property)因此。请参阅cellForRowAtIndexPath在下面的列表中。

就实现的具体细节而言,基于您正在阅读 http://news.yahoo.com/rss/ 的提要,我对这个答案进行了重大修改。它的格式与示例 XML 列表中显示的格式明显不同。格式实际上看起来是:

<item>
  <title>Palestinian death toll ...</title>
  <description>this contains the html version of the story description</description>
  <link>http://news.yahoo.com/palestinian-death-toll-...</link>
  <pubDate>Mon, 19 Nov 2012 11:20:15 -0500</pubDate>
  <source url="http://www.reuters.com/">Reuters</source>
  <guid isPermaLink="false">palestinian-death-toll-...</guid>
  <media:content url="http://the.url.for.image/images/palestinian.JPG" type="image/jpeg" width="130" height="86"></media:content>
  <media:text type="html">another html version of the text</media:text>
  <media:credit role="publishing company"></media:credit>
</item>

其中一些只是标准 XML 标签 title , description等,您要获取打开标签和关闭标签之间的值(为此您可以使用 NSXMLParserDelegate 方法 parser:foundCharacters: )。但图片URL实际上是在url里面media:content 的属性标签本身,在这种情况下您必须使用 NSXMLParserDelegate方法didStartElement并查询attributes参数。

因此,鉴于此,我上传了 sample Yahoo News reader它演示了解析 Yahoo RSS feed 的过程。请注意,这是一个相当原始的实现,但希望这能给您基本的想法。

关于objective-c - 如何显示来自 RSS 源的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13457215/

相关文章:

ios - UIAlertController 不是窗口层次结构

ios - NSDictionary 值发生变化而无需任何修改

ios - 无法在导航栏中心设置titleView,因为返回按钮

ios - 使用 TableView 进行 NSData 卸载

ios - 有没有办法同时运行多个 iOS 模拟器?

ios - UITextView 在键盘打开计算时调整大小

objective-c - NSDictionary 不会填满

ios - 使用json从本地文件传递数据

objective-c - UIResponder 链题

iOS 7 View 布局和半透明效果