import SwiftUI
struct ContentView: View {
@State private var resultText = ""
@State private var isLoading = false
var body: some View {
VStack(spacing: 20) {
Text("Network Call Example")
.font(.title)
Button("Fetch Data") {
Task {
await fetchData()
}
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
if isLoading {
ProgressView()
}
Text(resultText)
.padding()
.multilineTextAlignment(.center)
}
.padding()
}
func fetchData() async {
isLoading = true
resultText = ""
let urlString = "https://jsonplaceholder.typicode.com/posts/1"
guard let url = URL(string: urlString) else {
resultText = "Invalid URL."
isLoading = false
return
}
do {
let (data, _) = try await URLSession.shared.data(from: url)
if let post = try? JSONDecoder().decode(Post.self, from: data) {
resultText = post.title
} else {
resultText = "Failed to decode data."
}
} catch {
resultText = "Network error: \(error.localizedDescription)"
}
isLoading = false
}
}
struct Post: Decodable {
let title: String
}
This solution uses SwiftUI with async/await to perform the network call when the user taps the 'Fetch Data' button.
The fetchData() function is marked async and uses URLSession.shared.data(from:) to get data from the URL.
We use do-catch to catch any errors during the network call. If successful, we decode the JSON into a Post struct and show the title.
The isLoading state controls showing a ProgressView while fetching.
If any error occurs, a friendly message is shown in resultText.