URLSession Networking in Swift

Tram Ho

Through this article, you will learn:

  • When to use URLSession
  • What is URLSession
  • Fetch data uses URLSession through a simple example

When to use URLSession

URLSession is a framework that Apple itself developed and implemented in iOS. A lot of developers use third-party libraries like Alamofire But you will soon realize that, you do not need to depend too much on a library to make a simple HTTP request, URLSession will have all the things you want.

What is URLSession

URLSession is a class that provides API to interact with protocols like HTTP, HTTPS

  • URLSession creates a session, it simply looks like an open tab in your browser, it contains many HTTP request methods that users can interact with.
  • URLsession is used to create URLSessionTask object, which you can retrieve data from Internet, download or upload files to webservices. There are 3 types of tasks:
    • URLSessionDataTask: Use this action for HTTP GET requests to retrieve data from the server into memory.
    • URLSessionUploadTask: Use this action to upload the file from disk to a web service, usually through the HTTP POST or PUT method.
    • URLSessionDownloadTask: Use this action to download files from remote services to the temporary file location. You can also pause, resume, and cancel tasks. URLSessionDownloadTask has additional pause capabilities for resuming in the future.
  • You can reconfigure a session with URLSesssionConfiguration for each purpose
    • .default: Create a default configuration object that uses object cache, credentials, and cache.
    • .ephemeral: Similar to the default configuration, except all session-related data is stored in memory. Think of this as a “private” session.
    • .background:Allows the session to perform background upload or download tasks. The transition continues even if the application is suspended or terminated by the system. URLSessionConfiguration also allows you to configure session properties such as timeout values, buffer policies, and additional HTTP headers. Refer to the documentation for the complete list of configuration options

Fetch data uses URLSession

In practice, the steps to get data from the webservice:

  1. Initialize the HTTP Request with URLSession
  2. Use URLSessionDataTask send request to retrieve data
  3. Print the types of data to be returned
  4. Check there is the correct data we need and Convert the data to JSON

Initialize HTTP Request with URLSession

We need a session and a URL like this

  1. Creates a reference to the URLSession Class with default configuration
  2. Create url with URL type, parameter is string

The URL used in this example is uers.json, Copy this path and paste it into the string

Use URLSessionDataTask to send request to get data

Create a dataTask with the function dataTask(with:completionHandler:) :

dataTask(with:completionHandler:) has 2 parameters passed: url initialized above and 1 completionHandle

  • data: type is Data, is the data you want to get from webservice,
  • response: The type is URLResponse, which gives us more information about the response of the request including length, encoding, HTTP status code, …
  • error: will contain error information that would occur if the request was not successful. If the request is successful, error = nil

At this point, a request has not been completed, it has just been initiated, to start sending the request add:

Print the types of data to be returned

See, please print the data types that are captured in completionHandle and see what it is

What do we have ?:

  • dataOptional(321 bytes), because the data is of type Data
  • response: have a style NSHTTPURLResponse is the subclass of URLResponse. Include Status Code : 200 (I’ll talk more below) and HTTP headers (you can refer here)
  • errornil. Luckily, there was no fault

Check for the correct data we need

When making an HTTP request, you need to authenticate at least the following:

  1. Will there be any errors? => check error
  2. The HTTP response code was returned as expected => check response
  3. Is the data returned in the correct format? => check data hay convert data sang JSON

Check error or not?

If there is an error then call a function to resolve it and exit. Or you can refer to the treatment: throw an error

Check response have OK ?

  • Here we consider whether response is the correct type of HTTP Response and the Status code is in the range 200 – 299 or not. If not, it will exit
  • The status code is the status of the request, eg {404, 400, 401, etc ..} is an error, also in the {200 … 299} of your request was successful.

Check data, convert to JSON

Use optional binding to cast the data type to a JSON string using the function jsonObject(with:options:) of the class JSONSerialization. By reading each character in the data and converting it to a JSON string, it’s like reading a book and the story will come to mind.

Another way that apple recommends using:

In the above code, if in try If the error is caught, it will be printed in catch

Oke Let’s see what the json output is, if it is the same uers.json do you expect:

Summary

Awesome ! Here is the entire code that we learned all day, through which we know

  • If you want at HTTP Request, use URLSession
  • URLSession Apple’s built-in iOS framework provides APIs for interacting with HTTP and HTTS request methods
  • How to create 1 URLSession
  • How to check errorresponsedata
  • How to convert to JSON


References:

https://learnappmaking.com/urlsession-swift-networking-how-to/

https://www.raywenderlich.com/567-urlsession-tutorial-getting-started

https://learnappmaking.com/swift-optionals-how-to/#optional-binding

Share the news now