Component - URLSession basics
This UI component demonstrates how to use URLSession in Swift to fetch data from the internet. It shows a simple screen with a button to start the download and a text area to display the result or error message.
This UI component demonstrates how to use URLSession in Swift to fetch data from the internet. It shows a simple screen with a button to start the download and a text area to display the result or error message.
UIViewController ├── UIButton (Fetch Data) └── UITextView (Result Display)
URLSession in Swift?URLSession is designed to manage network tasks like downloading or uploading data.URLSession.URLSession?dataTask(with:completionHandler:) on URLSession.shared.data, response, error. Others have wrong method names or missing parameters.let url = URL(string: "https://example.com")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
print("Data received: \(data.count) bytes")
} else {
print("No data")
}
}
task.resume()data contains the downloaded bytes, so data.count is a positive number.let url = URL(string: "https://example.com")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
DispatchQueue.main.async {
print("Data length: \(data.count)")
}
}
}
// Missing task.resume()task.resume() to start the network request.let url = URL(string: "https://api.example.com/data")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else { return }
let text = String(data: data, encoding: .utf8) ?? "No data"
// Update label here
}
task.resume()
Options:DispatchQueue.main.async to update the label safely. Update label.text directly inside the closure without DispatchQueue risks UI bugs. Call label.text = text before task.resume() updates UI before data is fetched. Use a background thread to update label.text wrongly uses background thread for UI.Pass the test and this pattern moves unknown