Understanding URLSession basics

The following code snippet shows a sample of a network request that loads the https://apple.com homepage:

import Foundation

let url = URL(string: "https://apple.com")!
let task = URLSession.shared.dataTask(with: url)
{
  data, response, error in
  print(data)
  print(response)
  print(error)
}

task.resume()

This is an elementary example: A URL is created, and then the shared URLSession instance is used to create a new dataTask. This dataTask is an instance of URLSessionDataTask and allows you to load data from a remote server. Alternatively, you could use a download task if you're downloading a file, or an upload task if you're uploading files to a web server. After creating the task, you must call resume on the task, because new tasks are always created in a suspended state.

If you run this sample in an empty playground, you'll find that the example doesn't work. Because the network request is made asynchronously, the playground finishes its execution before the network request is complete. To fix this, you should make sure that the playground runs indefinitely. Doing so will allow the network request to finish. Add the following lines to the top of the playground source file to enable this behavior:

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

Now that the playground runs indefinitely, you'll find that there isn't a lot of useful data printed to the console. In this case, you're not interested in the raw data, HTTP headers, or the fact that the error is nil. When you load data from a URL, you're often most interested in the response's body. The body of a response usually contains the string representation of the data you requested. In the case of the preceding example, the body is the HTML that makes up Apple's homepage. Let's see how you can extract this HTML from the response. Replace the data task's completion callback with the following:

{ data, response, error in
  guard let data = data, error == nil
    else { return }

  let responseString = String(data: data, encoding: .utf8)
  print(responseString)
}

The preceding callback closure makes sure that there are no errors returned by the web service and that there is data present. Then, the raw data is converted to a string, and that string is printed to the console. If you use this callback instead of the old one, you'll see the HTML for the Apple homepage printed. Simple requests to a web server like the one you just saw are relatively simple to implement with URLSession.

You can take more control over the request that's executed by creating a URLRequest instance. The example you saw is one where you let URLSession create the URLRequest on your behalf. This is fine if you want to perform a simple HTTP GET request with no custom headers, but if you're going to post data or include specific headers, you will need to have more control over the request that's used. Let's take a look at what a GET request with some parameters and a custom header looks like.

The following code uses an API key from https://www.themoviedb.org/. If you want to try this code example, create an account on their website and request an API key on your account page. Setting this up should only take a couple of minutes, and if you want to follow along with this chapter, you will need to have your own API key:

let api_key = "YOUR_API_KEY_HERE"
var urlString = "https://api.themoviedb.org/3/search/movie/"
urlString = urlString.appending("?api_key=(api_key)")
urlString = urlString.appending("&query=Swift")

let movieURL = URL(string: urlString)!

var urlRequest = URLRequest(url: movieURL)
urlRequest.httpMethod = "GET"
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")

let movieTask = URLSession.shared.dataTask(with: urlRequest) { data, response, error in
  print(response)
}

movieTask.resume()

The preceding code is a bit more complicated than the example you saw before. In this example, a more complex URL is configured that includes some HTTP GET parameters. The httpMethod for URLRequest is specified, and a custom header is provided to inform the receiver of this request about the type of response it would like to receive.

The flow for executing this URL request is the same as the one you saw earlier. However, the URL that is loaded responds with a JSON string instead of an HTML document. JSON is used by many APIs as the preferred format to pass data around on the web. In order to use this response, the raw data must be converted to a useful data structure. In this case, a dictionary will do. If you haven't seen or worked with JSON before, it's a good idea to take a step back and read up on the JSON data format because this chapter will continue under the assumption that you are at least somewhat familiar with JSON.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.120.133