import SwiftUI
struct APIConnectionDemoView: View {
@State private var message: String = ""
@State private var isLoading: Bool = false
@State private var showError: Bool = false
var body: some View {
VStack(spacing: 20) {
Text("API Connection Demo")
.font(.title)
Button("Fetch Message") {
fetchMessageFromServer()
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
if isLoading {
ProgressView()
}
Text("Message: \(message)")
.padding()
}
.padding()
.alert(isPresented: $showError) {
Alert(title: Text("Error"), message: Text("Failed to fetch message."), dismissButton: .default(Text("OK")))
}
}
func fetchMessageFromServer() {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts/1") else { return }
isLoading = true
message = ""
showError = false
let task = URLSession.shared.dataTask(with: url) { data, response, error in
DispatchQueue.main.async {
isLoading = false
if let error = error {
print("Error: \(error.localizedDescription)")
showError = true
return
}
guard let data = data else {
showError = true
return
}
if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let title = json["title"] as? String {
message = title
} else {
showError = true
}
}
}
task.resume()
}
}
struct APIConnectionDemoView_Previews: PreviewProvider {
static var previews: some View {
APIConnectionDemoView()
}
}
This app screen has a button labeled 'Fetch Message'. When you tap it, the app calls a server API using URLSession. It fetches a simple JSON object from a test server. The app extracts the 'title' from the JSON and shows it below the button.
While waiting for the server, a spinning ProgressView appears to show loading. If the call fails, an alert pops up to tell the user there was an error.
This shows how API integration connects your app to servers to get data dynamically, instead of hardcoding it inside the app.