A simple RSS reader with the NSXMLParser for Objective - C.
I made my first iPhone app that shows a RSS feed from this blog and used the NSXMLParser in Objective C to do it. It was pretty easy to find RSS nodes I needed to to create the labels for the app.
The XML feed given back by the RSS for my blog has a couple of nodes I have to dig through to get to the items I need. The first is the channel node, this node holds all of the RSS info. The second is the item node, that holds each post of my blog. This is the node we need to get each link and title for the app. This function is what is called when the feed comes back from the web.
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)fName attributes:(NSDictionary *)attributeDict
{
if (fName) {
elementName = fName;
}
if (parsedFeedsCounter >= MAX_FEEDS) {
[parser abortParsing];
}
These next if statements look for the element string to further dig into the XML nodes and puts that data into the the currentFeedObject so that the next if statements can use this node to get the title and link info.
if ([elementName isEqualToString:@"item"]) {
parsedFeedsCounter++;
self.currentFeedObject = [[Feed alloc] init];
[(id)[[UIApplication sharedApplication] delegate] performSelectorOnMainThread:@selector(addToFeedList:) withObject:self.currentFeedObject waitUntilDone:YES];
return;
}
if ([elementName isEqualToString:@"title"]) {
self.contentOfCurrentFeedProperty = [NSMutableString string];
} else if ([elementName isEqualToString:@"link"]) {
self.contentOfCurrentFeedProperty = [NSMutableString string];
} else {
// The element isn’t one that we care about, so set the property that holds the
// character content of the current element to nil. That way, in the parser:foundCharacters:
// callback, the string that the parser reports will be ignored.
self.contentOfCurrentFeedProperty = nil;
}
}
Next I call a function when the parser is finished with each node to put each title and link objects into an array that will then be used for my app list.
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)fName
{
if (fName) {
elementName = fName;
}
if ([elementName isEqualToString:@"title"]) {
self.currentFeedObject.title = self.contentOfCurrentFeedProperty;
}
if ([elementName isEqualToString:@"link"]) {
self.currentFeedObject.webLink = [NSString stringWithFormat:@"%@", self.contentOfCurrentFeedProperty];
}
}
And that’s pretty much it for the XML parsing. It’s pretty simple to use the NSXMLParser in Objective C. I don’t have this app on the App Store but maybe if I get enough comments I’ll think about putting it up there.