DPS923 notes – Tue Feb 17

An introduction to accessing the network from an iOS app.


Important things to know before you begin coding

There are some very important things to know before you begin coding network tasks:

Basic knowledge of HTTP is required. You must know what a ‘request’ is, and what a ‘response’ is. These are the fundamental building blocks in an app that uses the network.

Basic knowledge of web services is required. You must know what a ‘web service’ is, and how to use one. In this course, you do not have to code/create a web service – you simply have to use one. You must also be able to understand and use JSON.

Network operations are asynchronous. That means that we do not know if or when our request will be responded to.

You must learn something about closures. A closure in Swift is an executable code object. Network operations use closures.

Simple tasks are easy to code, but complex tasks require more study. Simple tasks include ‘get one’ and ‘get all’ from a resource. More complex tasks include HTTP POST, data modifications, authentication, and so on.


Getting started, hands-on

This week, you will use the ClassesV2 template to create a simple app that uses a web service.

Download the ClassesV2 template from the GitHub code example repository. Then, perform the project-rename task.

We will use a public web service that your professor created recently. It is here:


It enables requestors to work with academic program data from the School of ICT. For example, you can obtain a collection of academic “Program” objects, or a collection of academic “Subject” objects. The web service is designed to be self-documenting, so you can discover its data and permitted operations.

By itself, a web browser is not a good tool to use to inspect a web service. Instead, use this web app:


Enter a resource URI in its “JSON Data Url” field, and click its “Process” button. The response to each request will be displayed in its own grey-bordered box. Try it with these URIs:





Composing a network request, and handling the response

In iOS (and OS X), we use a ‘task’ object to compose a network request, and handle the response.

The ‘task’ object is an instance of NSURLSessionDataTask. It uses a ‘session’ object, and a ‘request’ object.

The ‘session’ object is an instance of NSURLSession, which represents a logical session between your app and a web service. A ‘session’ object must be configured, using a ‘session configuration’ object (which is an instance of NSURLSessionConfiguration).

The ‘request’ object is an instance of NSMutableURLRequest, which needs a ‘URL’ object, and can be configured with request headers if necessary.

In summary, a ‘task’ object relies on the presence of a number of other initialized and configured objects.


Configuring and executing the ‘task’ object

When a ‘task’ object is created, it does not immediately execute. You must execute it, when you are ready, by sending the ‘resume’ message to the object. The ‘task’ object executes in the background, so it does not impair the responsiveness of your app’s user interface.

More important is the configuration of the ‘task’ object: You must write a block of code that will run when the task completes execution.

This block of code is known as a closure in Swift. Think of a closure as an inline function. (You have likely worked with similar constructs in the past, including JavaScript functions (and closures), and C# lambda expressions.)

The closure is defined on the ‘task’ object’s completionHandler parameter. It exposes these values:

  • The data returned in the response body
  • Metadata about the response
  • If necessary, error information

The data type of the data returned in the response body is NSData. Therefore, we must transform it into the format we expect. In this course, we plan to work with web services that use JSON, so we will transform the NSData object to JSON and then to an array or dictionary, as appropriate for the request.


Code example

See the “ICT WS v1” code example on the GitHub code example repository, in the Week_06 folder.


Learning resources

URL Loading System Programming Guide (a summary will be added below)


A deeper look at the networking classes

The following is a summary of the important parts of the URL Loading System Programming Guide, as well as the class reference documents for NSURLSession and others.

Content copied directly/verbatim from the Apple documentation is blue-coloured.

The URL loading system is a set of classes and protocols that allow your app to access content referenced by a URL.

The most commonly used classes in the URL loading system allow your app to retrieve the content of a URL from the source. In iOS 7 and later or OS X v10.9 and later, NSURLSession is the preferred API for new code that performs URL requests. Old code examples and search engine results will use other classes (NSURLConnection, AFNetworking). While useful and instructive, you should not rely on old code examples.

The URL loading classes use two helper classes that provide additional metadata—one for the request itself (NSURLRequest) and one for the server’s response (NSURLResponse).

The NSURLSession class and related classes provide an API for downloading content via HTTP. Like most networking APIs, the NSURLSession API is highly asynchronous. If you use the default, system-provided delegate, you must provide a completion handler block that returns data to your app when a transfer finishes successfully or with an error. 

The NSURLSession API supports three types of sessions. We will use the “default session” type.

Within a session, the NSURLSession class supports three types of tasks: data tasks, download tasks, and upload tasks. We will mostly use “data tasks”.

The NSURLSession API provides a wide range of configuration options. Most settings are contained in a separate configuration object (which is an instance of NSURLSessionConfiguration).

For many of our getting-started examples, when you instantiate an NSURLSession object, you specify the following: 

  1. A configuration object that governs the behavior of that session and the tasks within it
  2. Optionally, a delegate object; however, we will use nilIf you do not provide a delegate, the NSURLSession object uses a system-provided delegate. 
  3. The name of an operation queue that performs the task specified in the completion handler block. We will use [NSOperationQueue mainQueue].

Your app can provide the request body content for an HTTP POST request in three ways. We will use an NSData object.

To upload body content with an NSData object, your app calls … the uploadTaskWithRequest:fromData:completionHandler: method to create an upload task, and provides request body data through the fromData parameter.  

The session object computes the Content-Length header based on the size of the data object.

Your app must provide any additional header information that the server might require—content type, for example—as part of the URL request object.


Life Cycle of a URL Session with System-Provided Delegates

Here is the basic sequence of method calls that your app must make and completion handler calls that your app receives when using NSURLSession with the system-provided delegate:

1. Create a session configuration. 

2. Create a session, specifying a configuration object, a nil delegate, and an operation queue.

3. Create task objects within a session that each represent a resource request. Write a completion handler block.

Each task starts out in a suspended state. After your app calls resume on the task, it begins downloading the specified resource.

When a task completes, the NSURLSession object calls the task’s completion handler.

When your app no longer needs a session, invalidate it by calling finishTasksAndInvalidate (to allow outstanding tasks to finish before invalidating the object).

Note: NSURLSession does not report server errors through the error parameter. The only errors your app receives through the error parameter are client-side errors, such as being unable to resolve the hostname or connect to the host. 

Server-side errors are reported through the HTTP status code in the NSHTTPURLResponse object. 











  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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: