如何一次解析一个RSS源列表?

时间:2013-02-05 19:01:13

标签: ios parsing rss

我基本上将RSS提要中的项目保存到数组中,然后将该数组放入另一个数组中以包含它们。例如,我正在努力通过章节保存一堆教育视频(每章都有一个RSS提要),所以我使用这个逻辑一次性使用MWFeedParser解析它们:

for (NSString *url in videosArray) {    
        NSURL *feedURL = [NSURL URLWithString:url];
        feedParser = [[MWFeedParser alloc] initWithFeedURL:feedURL];
        feedParser.delegate = self;
        feedParser.feedParseType = ParseTypeFull;
        feedParser.connectionType = ConnectionTypeAsynchronously;
        [feedParser parse];
        }

虽然这样做,但如果第3章RSS提要在第2章之前完成解析,第3章的内容将保存在第2章的位置。虽然这听起来像是一个不必要的复杂解释,但我的要求就是:

有没有办法从Feed列表中一次解析一个Feed而不是继续,直到完全解析了一个feed它的内容被插入到数组中?

如果有帮助,这里有4个可能有用的委托方法:

- (void)feedParserDidStart:(MWFeedParser *)parser {
NSLog(@"Started Parsing: %@", parser.url);
}

- (void)feedParser:(MWFeedParser *)parser didParseFeedInfo:(MWFeedInfo *)info {
NSLog(@"Parsed Feed Info: “%@”", info.title);
self.title = info.title;
}

- (void)feedParser:(MWFeedParser *)parser didParseFeedItem:(MWFeedItem *)item {
NSLog(@"Parsed Feed Item: “%@”", item.title);
if (item) [parsedItems addObject:item];
}

- (void)feedParserDidFinish:(MWFeedParser *)parser {
NSLog(@"Finished Parsing%@", (parser.stopped ? @" (Stopped)" : @""));
[courseBeingBuilt.mediaCollection addObject:parsedItems]; // Place chapter contents into Course's Chapter w/contents array
parsedItems = [[NSMutableArray alloc] init]; // Create new array for new chapter
}

谢谢你们!

2 个答案:

答案 0 :(得分:3)

听起来您可以跟踪变量中的videosArray内的索引(例如NSUInteger currentIndex),并使用feedParserDidFinish:方法中的索引开始解析下一个Feed。

编写以下方法:

- (void) parseNextVideo
{
    NSURL *feedURL = [NSURL URLWithString:[videosArray objectAtIndex:currentIndex++]];
    feedParser = [[MWFeedParser alloc] initWithFeedURL:feedURL];
    feedParser.delegate = self;
    feedParser.feedParseType = ParseTypeFull;
    feedParser.connectionType = ConnectionTypeAsynchronously;
    [feedParser parse];
}

而不是for循环,只需:

currentIndex = 0;
[self parseNextVideo];

然后在feedParserDidFinish:

NSLog(@"Finished Parsing%@", (parser.stopped ? @" (Stopped)" : @""));
[courseBeingBuilt.mediaCollection addObject:parsedItems]; // Place chapter contents into Course's Chapter w/contents array
parsedItems = [[NSMutableArray alloc] init]; // Create new array for new chapter
if (currentIndex < videosArray.count) {
    [self parseNextVideo];
}

答案 1 :(得分:1)

不要让所有这些解析器同时松散,而是让你的委托对象变得更聪明:让它保留一个尚未解析的源URL的可变数组。当您调用feedParserDidFinish:时,请创建下一个解析器并从列表中删除其URL。如果阵列中没有剩余的Feed,那么你就完成了。

您还应该实现指示失败的委托方法,因为您可能会遇到单个订阅源的不可恢复错误(URL中不存在订阅源),影响所有网络操作的暂时性错误(网络连接丢失)或某些其他不良情况。您需要适当地处理这些案例。