Junior — Middle
Can you explain what URLSession is and how it is used for network requests in iOS?
sobes.tech AI
Answer from AI
URLSession is a class in iOS used for performing network requests, such as downloading data from web servers or sending data to a server.
It allows creating tasks for downloading or uploading data asynchronously, which does not block the main thread of the application.
Example of using URLSession to download data:
let url = URL(string: "https://api.example.com/data")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
// Handling received data
print("Data received: \(data)")
} else if let error = error {
print("Error: \(error.localizedDescription)")
}
}
task.resume() // Starting the task
Thus, URLSession simplifies working with HTTP requests and allows efficient management of network operations in iOS applications.