Question

I'm trying to grab images out of the cdata of an rss feed - I can get the images just fine and can add them to a mutablearray, but when I log the array, it always only contains the most recent image url - help?

This is what I've got:

- (void)viewDidLoad {
    [super viewDidLoad];
    NSXMLParser *parser = [[NSXMLParser alloc]initWithContentsOfURL:[NSURL URLWithString:@"http://somewebsite.com/feed"]];
    [parser setDelegate:self];
    [parser parse];
    NSLog(@"VIEWDIDLOAD SAYS: %@",self.imageURLS);
}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    element = elementName;
    if ([element isEqualToString:@"item"] || [element isEqualToString:@"entry"]) {
        self.imageURLS = [[NSMutableArray alloc]init];
        description = [[NSMutableString alloc] init];
    }
}

- (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock {
    if([element isEqualToString:@"description"]) {
        self.imageSource = nil;

        NSString *someString = [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];
        self.imageSource = [self getFirstImageUrl:someString];

        if (self.imageSource)
            NSLog(@"IMAGE URL STRING %@", self.imageSource);
    }
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    if ([element  isEqualToString:@"description"]) {
        [self.imageURLS addObject:self.imageSource];
        NSLog(@"ImageURLS: %@", self.imageURLS);
    }
}

-(NSString *)getFirstImageUrl: (NSString *) html {
    NSScanner *theScanner;
    NSString *imageURL = nil;

    theScanner = [NSScanner scannerWithString: html];

    // find start of tag
    [theScanner scanUpToString: @"<img" intoString: NULL];
    if ([theScanner isAtEnd] == NO) {

        [theScanner scanUpToString: @"src=\"" intoString: NULL];
        NSInteger newLoc2 = [theScanner scanLocation] + 5;
        [theScanner setScanLocation: newLoc2];

        // find end of tag
        [theScanner scanUpToString: @"\"" intoString: &imageURL];
    }

    return imageURL;
}
Was it helpful?

Solution

You are saying:

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    element = elementName;
    if ([element isEqualToString:@"item"] || [element isEqualToString:@"entry"]) {
        self.imageURLS = [[NSMutableArray alloc]init];
        description = [[NSMutableString alloc] init];
    }
}

This is unlikely to be right, because it means that every time you encounter a new "item" or "entry" element, you are throwing away the existing self.imageURLS and replacing it with an empty array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top