Database Reference
In-Depth Information
(NSHTTPURLResponse *) response;
if ([httpresp statusCode] == 404) {
[self handleError:@"Page not found!"];
} else {
[self displayResponse:data];
}
}
}
}];
}
So, what's going on here? Most of the action takes place in the showNews method, which
is triggered by the button push of the new tab bar item. When it is pressed, the code
creates an NSURL reference to the CNN website, and then creates an NSURLRequest
HttpRequest instance using the requestWithURL method. There are a number of param-
eters you can set on the returned object, some of which I cover later, but by default,
you get an HTTP GET request. Next, we use the sendAsynchronousRequest method of
the NSURLConnection class to actually perform the request. This method is handed three
parameters: the request we just created, the NSOperationQueue to run the request on
(which, for thread safety, will usually be the current queue), and a block which serves
as the completion handler (that is, the handler that deals with successful or failed calls).
If the request fails catastrophically (connection failures, server failures, etc.), the failure
is returned in the error parameter, which will be non-null. If the call succeeds, which
can include 401 (unauthorized) and 404 (not found) errors, the call response is popu-
lated along with the body of the response as an NSData object. You can proceed to
process the response body, returned in the data parameter.
If we run the application and click on the tab bar button, we get the expected results,
shown in Figure 4-1 .
If we change the hardwired string that we use to create the URL to something bogus,
such as http://www.cnnbuggywhip.com , we get an alert message with the error shown
in Figure 4-2 .
But suppose we specify a valid host name, but an invalid address, such as http://
www.cnn.com/buggywhipco.html? As I mentioned, a 404 error is considered a success
and will call the success selector, leading to something like the alert in Figure 4-3 .
What we really want to have happen here is to display a meaningful alert message,
something that we could internationalize, for example. So, we need to look a bit more
carefully at allegedly “good” responses, leading to the rewritten method shown in
Example 4-2 .
 
Search WWH ::




Custom Search