来自RSS Feed的图片

时间:2014-07-07 20:58:58

标签: ios objective-c xml cocoa-touch rss

我无法弄清楚如何从我的RSS Feed中获取图片网址。我得到了这样的其他元素:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if ([elementName isEqualToString:@"category"]) {
    }
    if ([elementName isEqual:@"title"])
    {
        currentString = [[NSMutableString alloc]init];
        [self setTitle:currentString];
    }
    else if ([elementName isEqual:@"link"])
    {
        currentString = [[NSMutableString alloc]init];
        [self setLink:currentString];
    }
    else if ([elementName isEqual:@"description"])
    {
        currentString = [[NSMutableString alloc]init];
        [self setInfoString:currentString];
    }
    else if ([elementName isEqual:@"pubDate"])
    {
        currentString = [[NSMutableString alloc]init];
        [self setDate:currentString];
    }

我需要从description元素中获取图片网址。

<description>
<![CDATA[
<img width="150" height="150" src="http://kyfbnewsroom.com/wp-content/uploads/2014/07/bevins-002-150x150.jpg" class="attachment-thumbnail wp-post-image" alt="Jimmy Bevins and Scott County FB President Jimmy Richardson at the current site." style="display: block; margin-bottom: 5px; clear:both;" />Toyota and urban sprawl have changed Scott County to where agriculture no longer is the dominant force. But farmers there still have clout, and the farm community is united and optimistic about agriculture’s future. Just ask Bill or Jimmy Bevins. They can tell you about the tremendous growth of the 68-year-old Bevins Motors farm equipment [&#8230;]
]]>
</description>

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Note: NSString *input would be your <description> element as a string        

    NSString *input = @"<description><![CDATA[<img width=\"150\" height=\"150\" src=\"http://kyfbnewsroom.com/wp-content/uploads/2014/07/bevins-002-150x150.jpg\" class=\"attachment-thumbnail wp-post-image\" alt=\"Jimmy Bevins and Scott County FB President Jimmy Richardson at the current site.\" style=\"display: block; margin-bottom: 5px; clear:both;\" />Toyota and urban sprawl have changed Scott County to where agriculture no longer is the dominant force. But farmers there still have clout, and the farm community is united and optimistic about agriculture’s future. Just ask Bill or Jimmy Bevins. They can tell you about the tremendous growth of the 68-year-old Bevins Motors farm equipment [&#8230;]]]></description>";

    NSString *urlString = [self getImageURLFromXML:input];

    if (urlString != nil)
    {
        // Use it
    }
    else
    {
        // No image link found
    }
}

- (NSString *)getImageURLFromXML:(NSString *)xml
{
    NSRange r1 = [xml rangeOfString:@"src=\""];
    NSString *extension;
    NSRange r2;

    if ([xml rangeOfString:@".jpg" options:NSCaseInsensitiveSearch].location != NSNotFound)
    {
        extension = @".jpg";
        r2 = [xml rangeOfString:@".jpg" options:NSCaseInsensitiveSearch];
    }
    else if ([xml rangeOfString:@".png" options:NSCaseInsensitiveSearch].location != NSNotFound)
    {
        extension = @".png";
        r2 = [xml rangeOfString:@".png" options:NSCaseInsensitiveSearch];
    }
    else if ([xml rangeOfString:@".gif" options:NSCaseInsensitiveSearch].location != NSNotFound)
    {
        extension = @".gif";
        r2 = [xml rangeOfString:@".gif" options:NSCaseInsensitiveSearch];
    }
    else
    {
        // Hmm some other weird image extension, or no extension found

        return nil;
    }

    NSRange rSub = NSMakeRange(r1.location + r1.length, r2.location - r1.location - r1.length);
    NSString *urlString = [xml substringWithRange:rSub];
    NSString *newUrlString = [NSString stringWithFormat:@"%@%@",urlString,extension];

    NSLog(@"String is: %@",newUrlString);

    // Output: String is: http://kyfbnewsroom.com/wp-content/uploads/2014/07/bevins-002-150x150.jpg

    return newUrlString;
}

答案 1 :(得分:0)

我想指出,<![CDATA[...]]> is a well-formed construct within XML。它允许添加数据,不会进一步解释为XML。或评论,二进制数据......

NSXMLParser知道如何通过委托方法-(void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock

来处理它

有了这个,我们可以一次获得整个块,将它传递给另一个解析器并检索信息。

这里我让同一个委托像根文档一样解析它。在现实世界的代码中,这应该重新考虑。

-(void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock
{
    self.cdatParser = [[NSXMLParser alloc] initWithData:CDATABlock];
    self.cdatParser.delegate = self;
    [_cdatParser parse];
}


-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{

    if (parser == _cdatParser) {
        if([elementName isEqualToString:@"img"]){
            NSLog(@"%@", attributeDict[@"src"]);
        }
    } else { // paser must be rootParser
        NSLog(@"%@", elementName);
    }
}

这将返回

http://kyfbnewsroom.com/wp-content/uploads/2014/07/bevins-002-150x150.jpg

  

我如何获得描述文字?

您可以执行以下操作以获取正确的xml并解析它

-(void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock
{
    NSString *cdataString = [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];
    cdataString = [cdataString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    cdataString = [NSString stringWithFormat:@"<description>%@</description>", cdataString];
    self.cdatParser = [[NSXMLParser alloc] initWithData:[cdataString dataUsingEncoding:NSUTF8StringEncoding]];
    self.cdatParser.delegate = self;
    [_cdatParser parse];
}

说明文字将发送到-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string


我的完整代码

#import "ViewController.h"

@interface ViewController ()<NSXMLParserDelegate>
@property (nonatomic, strong) NSXMLParser *rootParser;
@property (nonatomic, strong) NSXMLParser *cdatParser;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"feed" ofType:@"xml"];

    NSError *e;
    NSString *contentOfFeed = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&e];
    if (contentOfFeed) {
        self.rootParser= [[NSXMLParser alloc] initWithData:[contentOfFeed dataUsingEncoding:NSUTF8StringEncoding]];
        self.rootParser.delegate = self;
        [self.rootParser parse];
    } else {
        NSLog(@"%@", e.localizedDescription);
    }


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{

    if (parser == _cdatParser) {
        if([elementName isEqualToString:@"img"]){
            NSLog(@"%@", attributeDict[@"src"]);
        }

        if([elementName isEqualToString:@"description"]){
            NSLog(@"start description");
        }
    } else { // paser must be rootParser
        NSLog(@"%@", elementName);
    }
}


-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{


        NSLog(@"%@: end %@", (_cdatParser)?@"cdata":@"root" ,elementName);

}


-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (parser == _cdatParser) {
        NSLog(@"cdata: %@", string);

    } else { // paser must be rootParser
        NSLog(@"root: %@", string);
    }
}


-(void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock
{
    NSString *cdataString = [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];
    cdataString = [cdataString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    cdataString = [NSString stringWithFormat:@"<description>%@</description>", cdataString];
    self.cdatParser = [[NSXMLParser alloc] initWithData:[cdataString dataUsingEncoding:NSUTF8StringEncoding]];
    self.cdatParser.delegate = self;
    [_cdatParser parse];
}


@end