Chapter 6. Networking and XML

6.0. Introduction

iOS applications can take advantage of iOS SDK networking and XML parsing classes in order to create richer and connected applications. Whether you are trying to download a new resource from the Internet into your application’s bundle or make a call to a web service, you can find various classes and functionalities in the SDK that will help you make the process much easier than you thought. The iOS SDK provides the NSXMLParser class to parse XML and the NSURLConnection class (among others) for web services.

In this chapter, we will go through the implementation and usage of these classes, and then mix them to parse remote XML files. We will also discuss caching mechanisms and how to implement a custom mechanism for specific needs.

6.1. Opening and Reading a Local XML File


You want to read the contents of an XML file that has been read into memory, perhaps into an instance of the NSData class.


Create an instance of NSXMLParser and provide it with a delegate that conforms to the NSXMLParser protocol:

  NSXMLParser *parser = [[NSXMLParser alloc] initWithData:nil];
  [parser setDelegate:self];
  [parser parse];

In this code, we are passing nil to the initWithData: method of the NSXMLParser. In this recipe’s Discussion, you will see how to load the contents of an XML file from our application bundle into an instance of NSData and pass it to the NSXMLParser to parse.


Instances of the NSXMLParser class are able to parse XML documents. ...

Get iOS 4 Programming Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.