Apple’s URL Loading System

Sohail Ur Rahman Shaik
4 min readMar 5, 2024

--

Many a times we usually work on URL requests, URLSession’s and API’s to do networking tasks and most of us just go through all the components in everyday tasks without knowing much of what is what.

So I will be covering all the components of an URL loading system so that we learn what are these components are and what kind of work they do in an networking ecosystem.

Apple’s URL loading system is a framework of classes available to interact with URL’s. We use these classes to communicate with services that use standard internet protocols. The classes that we are using in everyday tasks are

  1. URLSession
  2. URLSessionConfiguration
  3. URLSessionTask
  4. URL
  5. URLRequest
  6. HTTPURLResponse

Let me go through each component in very simple terms so that we remember what kind of task is done by which component.

  1. URLSession : URLSession is a tool in Swift that lets your app communicate with other computers over the internet, getting and sending data back and forth. Like other networking(AFNetworking which is written in objective c though) URLSession is Asynchronous which means your app doesn’t wait for the response before continuing to execute other code. When the response to the request is received, URLSession will notify your app, typically by calling a completion handler that you provide.
  2. URLSessionConfiguration: It helps you set up the rules and options for how your app will interact with the internet. This class defines the behaviour and policies to use when using URLSession object to connect to a URL. When using the URLSession object, We usually create a URLSessionConfiguration instance first, because an instance of this class is required when we create an instance of the URLSession class. There are 3 session types
  • Default session configuration : This manages upload download tasks with default configuration
  • Ephemeral session configuration: This is same like default except it does not cache anything to disk. Mainly used to create private browsing session, security and does not store cache, history or cookies.
  • Background session configuration: It allows uploads and downloads large files, like videos or updates, even when the app is not actively running.

3. URLSessionTask: The URLSession service uses an instance of URLSessionTask class to make the call to the service that we are connecting to. The URLSessionTask class is the base class and provides three subclasses namely URLSessionDataTask, URLSessionDownloadTask and URLSessionUploadTask. Its important to note that a task will not send the request to the service until we call the resume() method

4. URL: The URL object represents the URL that we are going to connect to. The URL class is not limited to URL that represents remote server, but can also be used to represent a local file on the disk

5. URLRequest: It encapsulates our URL and request properties. It is important to understand that URLRequest class has all the necessary information to make our request, but it does not make the actual request. To make the request, we use instances of the URLSession and URLSessionTask classes.

6. HTTPURLResponse: This is a subclass of URLResponse class, which encapsulates the metadata associated with the response to a URL request. This class allows us to access the HTTP header fields and reponse status codes.

Below is the code using all the above components

import Foundation

// Define the base URL for the GET request
let baseURLString = "https://urlplaceholder.com/posts"

// Create an ephemeral URLSessionConfiguration.You can use default here based on your need
let configuration = URLSessionConfiguration.ephemeral

// Create a URLSession with the ephemeral configuration.
let session = URLSession(configuration: configuration)

// Define query items
let queryItems = [
URLQueryItem(name: "userId", value: "1"),
URLQueryItem(name: "title", value: "Apple URL Loading System")
]

// Create URL components
var urlComponents = URLComponents(string: baseURLString)
urlComponents?.queryItems = queryItems

// Create a URLRequest with the URL
guard let url = urlComponents?.url else {
fatalError("Invalid URL")
}
var request = URLRequest(url: url)
request.httpMethod = "GET"

// Create a data task with the request
let task = session.dataTask(with: request) { (data, response, error) in
// Check for errors
if let error = error {
print("Error: \(error.localizedDescription)")
return
}

// Check for response and data
guard let httpResponse = response as? HTTPURLResponse,
let data = data else {
print("Invalid response or data")
return
}

// Print the HTTP status code
print("HTTP Status Code: \(httpResponse.statusCode)")

// Print the response body as a string
if let responseBody = String(data: data, encoding: .utf8) {
print("Response Body: \(responseBody)")
}
}

// Resume the task
task.resume()

Now I hope you are able to correlate what we learned so far with the swift code above.

And That’s it… Thank you for taking time to read it. If you have any questions or thoughts to share, please feel free to leave a comment below.

Happy Learning 💫

--

--