URLSession: Network Communication in Swift
Smartphones allow you to hold an enormous amount of computing power in the palm of your hand. Still, to be truly useful most apps need to communicate with other systems to receive and send data. iOS provides a collection of built-in classes that will make sending and receiving data from your app much easier. The URLSession
class and its related classes offer the simplest way to create a network request and receive data in response.
Before we start building an app, let’s look at the basics of creating a URLSession
request in a Playground and then take a deeper look at how URL requests are made in Swift. For this exercise we’ll use a free NASA API that returns data about Near Earth Objects. (You’ll need to register for your own API key.)
//: Playground - noun: a place where people can play
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
var request = URLRequest(url: URL(string: "https://api.nasa.gov/neo/rest/v1/feed?start_date=2020-10-05&end_date=2020-10-09&api_key=DEMO_KEY")!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is (httpStatus.statusCode)")
print("response = \(response)")
}
if let body_response = String(data: data, encoding: String.Encoding.utf8) {
print(body_response)
}
}
task.resume()
Let’s look at what this bit of code does to return data. Note that the needsIndefiniteExecution
property must be set to true however in order to keep the playground active while the task is waiting for a response.
First, create an instance of URLRequest
which will hold the necessary properties of your network request including the target URL and the HTTP request method.
You will need a URLSession
to manage your network requests. For simple networking tasks, Apple provides a singleton (shared) instance of URLSession
that can be used by your app. There are strict limits on how much you can customize this shared session so if you have special requirements, you’ll need to create and configure your own instance of URLSession
. Creating custom session instances will be covered in a later article.
Within the URLSession
, you need to create a session task so that the request can be assigned to it and the task can be executed later. In this case we have used a dataTask
which returns the data received from the request to memory where it can be operated on by the app. There are also special tasks for downloading and upload files, streaming and web sockets. For now the dataTask
is all you need.
The dataTask
takes a completion handler that will be executed once the response is received. As you create the task, you provide both the request object defined above and the completion handler code that will handle the results of the request.
In the completion handler, you need perform a few validations on the task response to make sure that we have usable data. First we need to make sure that the request didn’t end with an error and that some data was returned. Now that we know we have received a response with data, check the HTTP status code – if it’s anything other than 200 we have a problem! Otherwise, it’s safe (for now) to assume that good data was returned. We take this data and attempt to encode it as a string.
With the request and completion handler defined, it’s time to make the request, but there is one more thing left to do. You have to tell Swift to actually do something with the task you’ve defined. When a session task is created, it is automatically created in a suspended state. Therefore, the task.resume()
statement tells the app to actually execute the request. If you leave this crucial step out, the request will never be made.
There you have it. If you’ve set up everything correctly, when the request finishes you will see a JSON object containing information about near earth objects. In upcoming articles, we’ll look at how to perform network requests in an iOS app, how to parse and use the data and how to work with custom sessions.