Introduction to network access in iOS

The best iOS apps rely on data from a network location. This document is an introduction to network access in iOS.

This document was most recently updated in October 2011.

.

Introduction to network operations in iOS

For most network operations, the typical use case is that the request and response is performed in an asynchronous manner. This is usually a good thing, because the network operation will not block the execution of your app’s other code.

This is an entry-level treatment of async network operations. A full and complete treatment is beyond the scope of this introductory iOS programming course. Be aware that there are more sophisticated ways of handling async tasks by performing them in the background.

.

There is a best practice pattern for coding iOS apps that perform asynchronous network operations. The pattern is summarized by the following steps:

  1. Configure an NSMutableData property to receive the response data from the network endpoint (i.e. a server)
  2. Create an NSURLRequest object, which typically requires a string URI
  3. Create an NSURLConnection object, which gets initialized with the request object

.

When the connection object is created, it immediately sends the request to the server. The connection object is designed to rely on delegate methods, which process the response from the server. Therefore, you must implement some delegate methods. Which ones? Read/skim the documentation for the NSURLConnection Class Reference for full details, but we suggest at least the following:

  • connection:didReceiveResponse:
  • connection:didReceiveData:
  • connectionDidFinishLoading:
  • connection:didFailWithError:

.

In the following section, you will learn the coding pattern for a network operation. A request will be sent to a local web service (using the URI from earlier in this post). The response will be returned as JSON. Then, a table view will be configured with the data. A table view row can be tapped, and details about the selected row will be displayed with a standard view controller.

.

Coding pattern

Two example apps from today, “TV via web”, and “Read Tweets”, implement the principles shown above, and the coding pattern discussed below.

First, configure the view controller with an NSMutableData property. The raw response is returned as NSData. It may require multiple responses to fully deliver the requested data, so we need a mutable NSData object.

Then, when you’re ready perform the request, initialize the property:

dataToBeLoaded = [[NSMutableData alloc] init];

Now, create an NSURLRequest object which requires an NSURL:

NSURL *url = [NSURL URLWithString:@"http://host.example.com/path/to/web/service/data"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

Next, create an NSURLConnection object, using the NSURLRequest:

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

Note that the initialization required you to name a delegate. The current view controller (i.e. “self”) will hold/implement the delegate methods.

Now, you’re ready to implement the delegate methods.

You don’t have to do much in connection:didReceiveResponse:. You may want to log a message to the debug console.

For connection:didReceiveData:, you will append data to the NSMutableData property. Depending upon the size of the incoming response, the Cocoa runtime may call this method multiple times.

After the last response package has been received, the server will close the connection, and the Cocoa runtime will call the connectionDidFinishLoading: method. In this method, you will convert the NSMutableData property into a string, and then use a method in the downloaded “json-framework” to convert it into an array, or a dictionary. (The “Consume JSON…” document will introduce you to the json-framework.)

Which one? Array or dictionary? If the first character of the JSON result is a square bracket ( [ ), convert it to an array. Alternatively, if the first character is a curly brace ( { ), convert it to a dictionary.

Incidentally, the “Read Tweets” example app requires a bit more learning:

The response data is in an object wrapper. The token “results” is the name/key for the object. The object itself is an array – which is the data we really want.

Therefore, we 1) assign the response data to a new NSDictionary object, and 2) then assign its objectForKey:@”results” to an NSArray property (which is a data-bearing property on the view controller).

The array holds the data that is needed for the table view. The only wrinkle at this point in time is that the table view has already been rendered; that happened when the view nib was unarchived. Therefore, now that we have the response data in the array, we have to reload the table view.

Check the “Read Tweets” example app for a full implementation. That code has been generously commented, so study the code carefully.

.

Destinations for web service results

There are a number of possibilities for handling the response data. You can choose to use it and discard it, or persist the data. Here are some choices:

  • Use the data in the current view controller, and then discard the data
  • Save the data in a plist or archive
  • Persist the data using Core Data
  • Send the data to another/a different web service endpoint

.

The plan is to cover some of these destinations in more detail, with additional posts and examples.

.


.

.

.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 47 other followers

%d bloggers like this: