0
0
iOS Swiftmobile~20 mins

Why API integration connects to servers in iOS Swift - Build It to Prove It

Choose your learning style9 modes available
Build: API Connection Demo
This screen shows a button that fetches a simple message from a server using API integration and displays it.
Target UI
-----------------------
| API Connection Demo  |
|---------------------|
|                     |
|  [Fetch Message]     |
|                     |
|  Message:           |
|                     |
|                     |
-----------------------
Add a button labeled 'Fetch Message'.
When tapped, the app calls a simple API on a server.
Display the returned message below the button.
Show a loading indicator while waiting for the server.
Handle errors by showing an alert.
Starter Code
iOS Swift
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") {
                // TODO: Add API call here
            }
            .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")))
        }
    }
}

struct APIConnectionDemoView_Previews: PreviewProvider {
    static var previews: some View {
        APIConnectionDemoView()
    }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
iOS Swift
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.

Final Result
Completed Screen
-----------------------
| API Connection Demo  |
|---------------------|
|                     |
|  [Fetch Message]     |
|                     |
|  Message: sunt aut   |
|           facere     |
|           repellat   |
-----------------------
User taps 'Fetch Message' button.
A loading spinner appears below the button.
After a moment, the message from the server appears.
If the server call fails, an error alert shows.
Stretch Goal
Add a refresh button to fetch the message again without restarting the app.
💡 Hint
Add another button that calls the same fetchMessageFromServer() function.