Bird
Raised Fist0
iOS Swiftmobile~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. Why does an iOS app use API integration to connect to servers?
easy
A. To speed up the app without internet
B. To change the app's color scheme locally
C. To increase the app's storage on the device
D. To get or send data like live updates or user info

Solution

  1. Step 1: Understand the purpose of API integration

    API integration allows the app to communicate with servers to exchange data.
  2. Step 2: Identify what connecting to servers achieves

    This connection helps the app get live information or save user actions online.
  3. Final Answer:

    To get or send data like live updates or user info -> Option D
  4. Quick Check:

    API integration = data exchange with servers [OK]
Hint: API integration means data exchange with servers [OK]
Common Mistakes:
  • Thinking API changes app colors locally
  • Believing API increases device storage
  • Assuming API speeds app without internet
2. Which Swift code snippet correctly starts a simple API request to a server?
easy
A. URLSession.shared.dataTask(url) { data, response in print(data) }
B. let task = URLSession.shared.dataTask(with: url) { data, _, _ in print(data) } task.resume()
C. URLSession.shared.request(url) { response in print(response) }
D. let task = URLSession.dataTask(url) { data in print(data) } task.start()

Solution

  1. Step 1: Check correct URLSession method usage

    The correct method is URLSession.shared.dataTask(with: url) with a completion handler.
  2. Step 2: Confirm how to start the task

    The task must be started by calling task.resume() to begin the request.
  3. Final Answer:

    let task = URLSession.shared.dataTask(with: url) { data, _, _ in print(data) } task.resume() -> Option B
  4. Quick Check:

    Correct URLSession syntax = let task = URLSession.shared.dataTask(with: url) { data, _, _ in print(data) } task.resume() [OK]
Hint: Use URLSession.shared.dataTask(with:) and call resume() [OK]
Common Mistakes:
  • Forgetting to call resume() to start the task
  • Using wrong method names like request()
  • Incorrect closure parameters in dataTask
3. What will this Swift code print if the server returns JSON data successfully?
let url = URL(string: "https://api.example.com/data")!
let task = URLSession.shared.dataTask(with: url) { data, _, error in
  if let data = data {
    print(String(data: data, encoding: .utf8) ?? "No data")
  } else {
    print("Error")
  }
}
task.resume()
medium
A. The JSON data as a string
B. Error
C. nil
D. Nothing prints

Solution

  1. Step 1: Analyze the dataTask completion handler

    If data is received, it converts data to a UTF-8 string and prints it.
  2. Step 2: Understand the output when server returns JSON

    The JSON data bytes convert to a readable string and print to console.
  3. Final Answer:

    The JSON data as a string -> Option A
  4. Quick Check:

    Data received = print JSON string [OK]
Hint: If data exists, it prints as string [OK]
Common Mistakes:
  • Assuming print("Error") always runs
  • Expecting nil instead of string output
  • Thinking nothing prints without resume()
4. Identify the error in this Swift code for API integration:
let url = URL(string: "https://api.example.com")
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
  if error != nil {
    print("Failed")
  } else {
    print("Success")
  }
}
medium
A. Closure parameters are incorrect
B. URL string is invalid
C. Missing task.resume() to start the request
D. Using URLSession.shared incorrectly

Solution

  1. Step 1: Check if the data task is started

    The code creates the task but never calls task.resume(), so the request never runs.
  2. Step 2: Confirm other parts are correct

    The URL is valid, closure parameters match, and URLSession usage is correct.
  3. Final Answer:

    Missing task.resume() to start the request -> Option C
  4. Quick Check:

    Without resume(), request won't run [OK]
Hint: Always call resume() to start URLSession tasks [OK]
Common Mistakes:
  • Forgetting to call resume()
  • Force unwrapping URL without checking
  • Misnaming closure parameters
5. You want your app to fetch user profile data from a server and update the UI only after the data arrives. Which approach correctly handles this API integration in Swift?
hard
A. Use URLSession dataTask with a completion handler, then update UI on the main thread inside the handler
B. Call URLSession dataTask and update UI immediately after task creation
C. Fetch data synchronously on the main thread to block UI until data arrives
D. Use URLSession dataTask without a completion handler and update UI later

Solution

  1. Step 1: Understand asynchronous data fetching

    URLSession dataTask runs asynchronously; UI updates must happen after data arrives.
  2. Step 2: Ensure UI updates happen on main thread

    Inside the completion handler, dispatch UI updates to the main thread to avoid errors.
  3. Final Answer:

    Use URLSession dataTask with a completion handler, then update UI on the main thread inside the handler -> Option A
  4. Quick Check:

    Async fetch + main thread UI update = Use URLSession dataTask with a completion handler, then update UI on the main thread inside the handler [OK]
Hint: Update UI on main thread inside completion handler [OK]
Common Mistakes:
  • Updating UI before data arrives
  • Blocking main thread with synchronous calls
  • Ignoring main thread for UI updates
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard