Getting some weather data in your iOS application

Introduction

If you’ve ever wanted to load up some weather data and display it in your iOS application, you’ve probably come across several different ways of doing it. Most examples I’ve seen use the built-in NSXMLParser class, which is a SAX parser… meaning it’s event driven and returns bits of the resulting XML data as they are loaded. That’s probably cool for large XML files, but generally speaking weather XML documents are usually very small. And nested. Nesting is the bane of NSXMLParser (in my humble opinion). You need to keep track of where you are in the document as the lines of XML stream through via delegates. It’s not pretty. It’s not impossible, but wouldn’t you rather use a DOM model parser… allowing you to use XPath to pull out the bits you need? Yes, me too.

KissXML

I found a handy wrapper for the libxml2 library (which is written in C). With it you load the entire XML file before traversing, you can read and generate XML, it has the same API as NSXML, behaves like NSXML and also behaves like a true Objective-C class. You can XPath the knickers off the resulting XML that resides in memory too. You can find the project page here and download the source, git it, whatever. Follow the instructions to bolt it into your application. Just remember to add the files to your project & add the compiler directives (2). Then #include “DDXML.h” where you’d like to use it. Getting started wiki page.

Google Weather

Let’s load up some weather data and parse it. If you’d like a sample bit of code showing you how to load up some weather data, I am including that below for reference. The DDXMLDocument object doesn’t have an initWithContentsOfURL but it does allow for initWithData. Perfect, we’ll just create the NSData ourselves.

Remember this is just an example… you can XPath the knickers to the ankles.

Not too shabby. No event delegates to muss with. No self-managed Booleans or counters. Traverse like a mouse in a maze if you’d like. Given the size of the returning XML, this approach is also wicked fast. So you if you’re coming from the AS3 Flash world, this is more what you’re used to. And for the case of nested documents, it’s much easier to use and to understand.