Chapter 26
XML Parsing, RSS and Expandable Table View Cells

One of the most important tasks that a developer has to deal with when creating applications is data handing and manipulation. Data can be expressed in many different formats, and mastering at least the most common of them is a key ability for every single programmer. Speaking of mobile applications specifically now, it's quite common nowadays for them to exchange data with web applications. In such cases, the way that data is expressed may vary, but usually uses either the JSON or the XML format.

The iOS SDK provides classes for handling both of them. For managing JSON data, there is the JSONSerialization class. This one allows developers to easily convert JSON data into a Foundation object, and the other way round. I have covered JSON parsing in chapter 4. In this chapter, we will look into the APIs for parsing XML data.

iOS offers the XMLParser class, which takes charge of doing all the hard work and, through some useful delegate methods gives us the tools we need for handling each step of the parsing. I have to say that XMLParser is a very convenient class and makes the parsing of XML data a piece of cake.

Being more specific, let me introduce you the XMLParserDelegate protocol we'll use, and what each of the methods is for. The protocol defines the optional methods that should be implemented for XML parsing. For clarification purpose, every XML data is considered as an XML document in iOS. Here are the core methods that you will usually deal with:

  • parserDidStartDocument - This one is called when the parsing actually starts. Obviously, it is called just once per XML document.
  • parserDidEndDocument - This one is the complement of the first one, and is called when the parser reaches the end of the XML document.
  • parser(_:parseErrorOccurred:) - This delegate method is called when an error occurs during the parsing. The method contains an error object, which you can use to define the actual error.
  • parser(_:didStartElement:namespaceURI:qualifiedName:attributes:) - This one is called when the opening tag of an element (e.g. ) is found.
  • parser(_:didEndElement:namespaceURI:qualifiedName:) - Contrary to the above method, this is called when the closing tag of an element (e.g. </title>) is found.
  • parser(_:foundCharacters:) - This method is called during the parsing of the contents of an element. Its second argument is a string value containing the character that was just parsed.

To help you understand the usage of the methods, we will build a simple RSS reader app together. The app will consume an RSS feed (in XML format), parse its content and display the data in a table view.

To continue reading and access the full version of the book, please get the full copy here. You will also be able to access the full source code of the project.

results matching ""

    No results matching ""