Я работаю над приложением школьной газеты для iPad с платформы. Я использую NSXMLParser для получения заголовков, кратких описаний и ссылок для каждой статьи. Чтобы получить элементы HTML из каждой проанализированной ссылки, я решил использовать анализатор Hpple. Я думаю, что я правильно разбираю и храню элементы RSS, но когда я пытаюсь проанализировать элементы HTML из каждой проанализированной ссылки, используя цикл for, он говорит мне, что у меня есть пустой массив для элементов RSS. Тем не менее, я могу отображать содержимое держателя элемента RSS на консоли. Таким образом, это не пусто. Я положу некоторую часть моего кода и отображения с консоли. Пожалуйста, помогите мне. Срок реализации этого проекта скоро. Заранее спасибо.
Вот как я начинаю загружать свой парсер RSS (articleParser):
- (void)loadData {
[self loadInitData];
//[self loadDataWithLink];
}
- (void)loadInitData {
if (sections == nil) {
[activityIndicator startAnimating];
NSLog(@"STARTING ARTICLE PARSER FROM MAIN URL!!!");
Parser *articleParser = [[Parser alloc] init];
[articleParser parseRssFeed:@"http://theaggie.org/rss/headlines.xml" withDelegate:self];
[articleParser release];
} else {
}
}
А ниже показано, как я сохраняю полученные элементы Article в массиве NSMutable, называемом «разделами». Затем я использовал цикл for для перебора каждой ссылки проанализированных статей.
- (void)receivedArticleItems:(Article *)theArticle {
if (sections == nil) {
sections = [[NSMutableArray alloc] init];
}
[sections addObject:theArticle];
NSLog(@"We recieved the article!");
NSLog(@"Article: %@", theArticle);
NSLog(@"What is in sections: %@", sections);
for (int i = 1; i < 5; i++) {
NSLog(@"articleItems: %@",[sections objectAtIndex:0]);
NSLog(@"articleItems at index 0: %@",[[[sections objectAtIndex:0] articleItems] objectAtIndex:0]);
[self loadDataWithLink:[[[[sections objectAtIndex:0] articleItems] objectAtIndex:0] objectForKey:@"link"]];
}
[activityIndicator stopAnimating];
}
Ниже показано, как я использовал анализатор TFFHpple для получения элементов HTML из каждой проанализированной ссылки:
- (void)loadDataWithLink:(NSString *)urlString{
NSData *htmlData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
// Create parser
TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
//Get all the cells main body
htmlElements = [xpathParser search:@"//div[@id='main']/div[@id='mainCol1']/div[@id='main-body']"];
// Access the first cell
TFHppleElement *htmlElement = [htmlElements objectAtIndex:0];
// NSString *title = [htmlElement content];
NSLog(@"What is in element: %@", htmlElement);
[xpathParser release];
//[htmlData release];
}
И вот что я получаю на консоли:
2011-05-02 22:58:35.355 TheCalAggie[2443:207] Parsing started for article!
2011-05-02 22:58:35.356 TheCalAggie[2443:207] Adding story title: Students say, 'No time for books'
2011-05-02 22:58:35.356 TheCalAggie[2443:207] From the link: http://theaggie.org/article/2011/05/03/students-say-no-time-for-books
2011-05-02 22:58:35.357 TheCalAggie[2443:207] Summary: The last book managerial economics major Kiyan Parsa read for fun was The Lord of the Rings. That was in high school.
2011-05-02 22:58:35.358 TheCalAggie[2443:207] Published on: Tue, 03 May 2011 00:00:00 -0700
2011-05-02 22:58:35.359 TheCalAggie[2443:207] Parsing started for article!
2011-05-02 22:58:35.360 TheCalAggie[2443:207] Adding story title: UC Davis craft center one of largest college crafting centers
2011-05-02 22:58:35.360 TheCalAggie[2443:207] From the link: http://theaggie.org/article/2011/05/02/uc-davis-craft-center-one-of-largest-college-crafting-centers
2011-05-02 22:58:35.361 TheCalAggie[2443:207] Summary: Hidden away in the South Silo, the UC Davis Craft Center offers 10 craft studios and more than a hundred classes for students looking to learn or perfect their crafting skills.
2011-05-02 22:58:35.362 TheCalAggie[2443:207] Published on: Mon, 02 May 2011 00:00:00 -0700
2011-05-02 22:58:35.362 TheCalAggie[2443:207] We recieved the article!
2011-05-02 22:58:35.363 TheCalAggie[2443:207] Article: *nil description*
2011-05-02 22:58:35.364 TheCalAggie[2443:207] What is in sections: (
(null)
)
2011-05-02 22:58:35.374 TheCalAggie[2443:207] articleItems: *nil description*
2011-05-02 22:58:35.375 TheCalAggie[2443:207] articleItems at index 0: {
link = "http://theaggie.org/article/2011/05/03/peaceful-rally-held-on-campus-after-killing-of-bin-laden\n";
pubDate = "Tue, 03 May 2011 00:00:00 -0700";
summary = "The announcement of Osama bin Laden's death sent a wave of patriotism across the nation and UC Davis. Bin Laden was the leader of al-Qaeda - the organization allegedly behind the Sept. 11, 2001 attacks that killed over 3,000 Americans.\n";
title = "Peaceful rally held on campus after killing of bin Laden \n";
}
2011-05-02 22:59:35.376 TheCalAggie[2443:207] Unable to parse.
2011-05-02 22:59:35.379 TheCalAggie[2443:207] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'
*** Call stack at first throw:
Любая помощь будет принята с благодарностью. Еще раз спасибо.