Build: Simple Fetch Screen
This screen fetches text data from a URL and shows it on screen.
Target UI
------------------------- | Simple Fetch Screen | |-----------------------| | [Fetch Data] | | | | | | | | | | | | | -------------------------
------------------------- | Simple Fetch Screen | |-----------------------| | [Fetch Data] | | | | | | | | | | | | | -------------------------
import SwiftUI struct SimpleFetchScreen: View { @State private var fetchedText = "" @State private var isLoading = false @State private var errorMessage = "" var body: some View { VStack(spacing: 20) { Button("Fetch Data") { // TODO: Add fetch code here } if isLoading { ProgressView() } if !errorMessage.isEmpty { Text(errorMessage).foregroundColor(.red) } ScrollView { Text(fetchedText) .padding() } Spacer() } .padding() .navigationTitle("Simple Fetch Screen") } } struct SimpleFetchScreen_Previews: PreviewProvider { static var previews: some View { SimpleFetchScreen() } }
import SwiftUI struct SimpleFetchScreen: View { @State private var fetchedText = "" @State private var isLoading = false @State private var errorMessage = "" var body: some View { VStack(spacing: 20) { Button("Fetch Data") { fetchData() } if isLoading { ProgressView() } if !errorMessage.isEmpty { Text(errorMessage).foregroundColor(.red) } ScrollView { Text(fetchedText) .padding() } Spacer() } .padding() .navigationTitle("Simple Fetch Screen") } func fetchData() { isLoading = true errorMessage = "" fetchedText = "" guard let url = URL(string: "https://www.example.com") else { errorMessage = "Invalid URL." isLoading = false return } URLSession.shared.dataTask(with: url) { data, response, error in DispatchQueue.main.async { isLoading = false if let error = error { errorMessage = "Error: \(error.localizedDescription)" return } guard let data = data, let text = String(data: data, encoding: .utf8) else { errorMessage = "Failed to load data." return } fetchedText = text } }.resume() } } struct SimpleFetchScreen_Previews: PreviewProvider { static var previews: some View { SimpleFetchScreen() } }
This solution uses URLSession.shared.dataTask to fetch data from the given URL asynchronously. We set isLoading to true before starting the fetch to show a loading spinner. When the fetch completes, we switch back to the main thread using DispatchQueue.main.async to update the UI states safely.
If there is an error, we show a red error message. If the data is successfully fetched, we convert it to a string and display it below the button. This simple pattern is the foundation for network calls in iOS apps.
------------------------- | Simple Fetch Screen | |-----------------------| | [Fetch Data] | | | | (loading spinner) | | | | <fetched text shown> | | | | | -------------------------
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