URLSession — Swift

BN
iOS World
Published in
2 min readFeb 12, 2023

URLSession is a class in the Foundation framework of Apple’s iOS and macOS operating systems. It provides an API for communicating with HTTP and HTTPS servers. With URLSession, you can make asynchronous network requests, download or upload data, and handle the responses from the server. URLSession provides a way to work with remote resources using a set of tasks and delegate-based callbacks. The tasks, such as data tasks and upload tasks, provide a way to initiate network requests and track their progress, while delegate-based callbacks provide a way to handle the response data and handle any errors that may occur.

URLSession also provides various configuration options, such as customizing timeouts, specifying the cache policy, and providing custom authentication credentials. The class is designed to be easy to use, while still providing a high level of control over the behavior of network requests.

Here is an example of how to use URLSession to perform a simple GET request in Swift:

let url = URL(string: "https://www.example.com")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let data = data {
let string = String(data: data, encoding: .utf8)
print(string)
}
}
task.resume()

In this example, we create a URL object using the URL initializer. We then create a data task using the dataTask(with:) method of URLSession, passing in the URL. The completion handler is passed as a closure that takes three arguments: data, response, and error. The data argument is the data received from the server, the response argument is an object that describes the response, and the error argument is an error that may have occurred during the request.

Here is an example of how to use URLSession to perform a simple POST request in Swift:

let url = URL(string: "https://www.example.com")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = "data=example".data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let data = data {
let string = String(data: data, encoding: .utf8)
print(string)
}
}
task.resume()

In this example, we create a URL object and a URLRequest object. We set the httpMethod property of the URLRequest object to "POST" and set the httpBody property to the data we want to send to the server. We then create a data task using the dataTask(with:) method of URLSession, passing in the URLRequest object. The completion handler is passed as a closure that takes three arguments: data, response, and error. The data argument is the data received from the server, the response argument is an object that describes the response, and the error argument is an error that may have occurred during the request.

--

--