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.