Graphics Programs Reference
In-Depth Information
At times, you will need to make a string “URL-safe.” For example, space characters and
quotes are not allowed in URLs; They must be replaced with escape-sequences. Here is
how that is done.
NSString *search = @"Play some \"Abba\"";
NSString *escaped =
[search stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// escaped is now "Play%20some%20%22Abba%22"
When the request to the Big Nerd Ranch forums is processed, the server will return XML
data that contains the last 20 posts. The
ListViewController
, who made the re-
quest, will populate its table view with the titles of the posts.
In
ListViewController.h
, add an instance variable for the connection and one for
the data that is returned from that connection. Also add a new method declaration.
@interface ListViewController : UITableViewController
{
NSURLConnection *connection;
NSMutableData *xmlData;
}
- (void)fetchEntries;
@end
Working with NSURLConnection
An
NSURLConnection
instance can communicate with a web server either synchron-
ously or asynchronously. Because passing data to and from a remote server can take some
time, synchronous connections are generally frowned upon because they stall your applic-
ation until the connection completes. This chapter will teach you how to perform an asyn-
chronous connection with
NSURLConnection
.
When an instance of
NSURLConnection
is created, it needs to know the location of the
web application and the data to pass to that web server. It also needs a delegate. When told
to start communicating with the web server,
NSURLConnection
will initiate a connec-
tion to the location, begin passing it data, and possibly receive data back. It will update its
delegate each step of the way with useful information.
In
ListViewController.m
, implement the
fetchEntries
method to create an
NSURLRequest
that connects to
http://forums.bignerdranch.com
and asks
for the last 20 posts in RSS 2.0 format. Then, create an
NSURLConnection
that trans-
fers this request to the server.