我试图从rss feed的cdata中抓取图像 - 我可以将图像很好地添加到mutablearray中,但是当我记录数组时,它总是只包含最新的图片网址 - 帮忙?
这就是我所拥有的:
- (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;
}
答案 0 :(得分:1)
你在说:
-(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];
}
}
这不可能是正确的,因为这意味着每次时间遇到 new &#34; item&#34;或&#34;条目&#34;你将扔掉现有的self.imageURLS
并用空数组替换它。