Magazine

Tutoriel sur la conception d’un lecteur de flux RSS simple : Téléchargement et utilisation des feeds

Publié le 19 juillet 2011 par Developpementiphone

mots-clés : developpement iphone, tutoriel, lecteur rss
Si vous étiez sur le point de lancer encore le programme, il n’y aurait toujours rien : nous n’avons pas ajouté encore la capacité de télécharger et d’utiliser les feeds, donc nous allons le faire maintenant.

Editez la méthode “viewDidAppear:” afin qu’elle ressemble comme ceci:

- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if ([stories count] == 0) {
NSString * path =  @”http://feeds.feedburner.com/TheAppleBlog”;
[self parseXMLFileAtURL:path];
}
cellSize = CGSizeMake([newsTable bounds].size.width, 60);
}

C’est ici que nous indiquons au parser quel feed à télécharger. Il appelle une méthode, que vous pouvez copier/coller dès à présent.

- (void)parseXMLFileAtURL:(NSString *)URL {
stories = [[NSMutableArray alloc] init];
//you must then convert the path to a proper NSURL or it won’t work
NSURL *xmlURL = [NSURL URLWithString:URL];
// here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
// this may be necessary only for the toolchain
rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];  // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
[rssParser setDelegate:self];
// Depending on the XML document you’re parsing, you may want to enable these features of NSXMLParser.
[rssParser setShouldProcessNamespaces:NO];
[rssParser setShouldReportNamespacePrefixes:NO];
[rssParser setShouldResolveExternalEntities:NO];
[rssParser parse];
}

C’est une méthode que nous ajoutons afin de créer le pointeur vide pour stories, créer un parser, et commencer le téléchargement du feed. Comme le parser fonctionne, ce contrôleur sur lequel nous travaillons va recevoir diverses méthode delegate, que vous pouvez copier/coller maintenant :

- (void)parserDidStartDocument:(NSXMLParser *)parser {  NSLog(@”found file and started parsing”);
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
NSString * errorString = [NSString stringWithFormat:@"Unable to download story feed from web site (Error code %i )", [parseError code]];
NSLog(@”error parsing XML: %@”, errorString); UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@”Error loading content” message:errorString delegate:self cancelButtonTitle:@”OK” otherButtonTitles:nil];
[errorAlert show];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
//NSLog(@”found this element: %@”, elementName);
currentElement = [elementName copy];
if ([elementName isEqualToString:@"item"]) {
// clear out our story item caches…
item = [[NSMutableDictionary alloc] init];
currentTitle = [[NSMutableString alloc] init];
currentDate = [[NSMutableString alloc] init];
currentSummary = [[NSMutableString alloc] init];
currentLink = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{ //NSLog(@”ended element: %@”, elementName); if ([elementName isEqualToString:@"item"]) {
// save values to an item, then store that item into the array…
[item setObject:currentTitle forKey:@"title"];
[item setObject:currentLink forKey:@"link"];
[item setObject:currentSummary forKey:@"summary"];
[item setObject:currentDate forKey:@"date"];
[stories addObject:[item copy]]; NSLog(@”adding story: %@”, currentTitle);
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//NSLog(@”found characters: %@”, string);
// save the characters for the current item…
if ([currentElement isEqualToString:@"title"]) {
[currentTitle appendString:string];
}
else if ([currentElement isEqualToString:@"link"]) { [currentLink appendString:string];
}
else if ([currentElement isEqualToString:@"description"]) { [currentSummary appendString:string];
}
else if ([currentElement isEqualToString:@"pubDate"]) { [currentDate appendString:string];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview]; NSLog(@”all done!”);
NSLog(@”stories array has %d items”, [stories count]);
[newsTable reloadData];
}

Malheureusement, le NSXLKParser le seul outil d’analyse de XML disponible sur l’iPhone. Cela signifie que nous devons explorer le fichier du haut vers le bas. Nous avons une série de chaînes de caractères à laquelle nous assignons des valeurs et ensuite que nous collectons sous forme de story items, qui sont sauvegarder un par un. Une fois qu’il rencontre le tag de fermeture d’”item”, il sauvegarde cette story, efface les champs, et commence sur le prochain item jusqu’à qu’il atteigne la fin du fichier.


Retour à La Une de Logo Paperblog

Dossier Paperblog