Database Reference
In-Depth Information
We can start by writing a utility function to generate the correct endpoint for the REST
request, given a series of parameters. By creating a stand-alone generator, it will be
easier to unit test that logic. So, we create a WebServiceEndpointGenerator class, with a
static method to create the appropriate endpoint, which looks like Example 4-4 .
Example 4-4. A web service endpoint generator
+(NSURL *) getForecastWebServiceEndpoint:(NSString *) zipcode startDate:(NSDate *)
startDate endDate:(NSDate *) endDate {
NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:@"YYYY-MM-dd'T'hh:mm:ss"];
NSString *url =
[NSString stringWithFormat:
@"http://www.weather.gov/forecasts/xml/\
sample_products/browser_interface/\
ndfdXMLclient.php?zipCodeList=%@\
&product=time-series&begin=%@\
&end=%@&maxt=maxt&mint=mint",
zipcode, [df stringFromDate:startDate],
[df stringFromDate:endDate]];
[df release];
return [NSURL URLWithString:url];
}
Back on our detail page, we add another bar button hooked up to a new selector, called
showWeather . To save some space here, and because we're interested in the backend
code, not the UI treatment, we'll have the success method for this call simply send the
output to the log using NSLog . But how to extract the useful data? We could use string
functions to find the pieces of the XML we were interested in, but that's laborious and
not very robust. We could use the XML pull parser that comes with iOS, but pull parsers
are also a bit of a pain, and I tend to avoid using them unless I need to significantly
parse down the in-memory footprint of the data. So, since iOS doesn't have a native
DOM parser, we'll dig one out of the open source treasure chest.
You actually have your choice of packages, TouchXML and KissXML. I prefer
KissXML, because it can both parse XML to a DOM, and generate XML from a DOM,
whereas TouchXML can only parse. KissXML is available at: http://code.google.com/p/
kissxml . Integration largely involves copying files into the project, adding the libxml2
library, and one additional step: adding a directory to the include search path. The
KissXML Wiki has all the details on how to add the package to your project.
I'll note here that KissXML is, at the moment, not compatible with the ARC compiler.
For that reason, I highly recommend making it into a static library that you include in
your main application, as described in Chapter 2 .
With the library in place, we can use XPath to pluck just the data we want out of the
returned payload from the web service; the code is shown in Example 4-5 .
 
Search WWH ::




Custom Search