Bird
Raised Fist0
iOS Swiftmobile~20 mins

Error handling for network calls in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Network Call Error Handling
This screen fetches data from a network URL and shows the result or an error message if the call fails.
Target UI
-------------------------
| Network Call Example   |
|-----------------------|
| [Fetch Data]          |
|                       |
| Result or Error here  |
|                       |
-------------------------
Add a button labeled 'Fetch Data' that triggers a network call.
Perform a simple GET request to https://jsonplaceholder.typicode.com/posts/1.
Display the fetched title text on success.
Show a user-friendly error message if the network call fails.
Use Swift's async/await and do-catch for error handling.
Show a loading indicator while fetching.
Starter Code
iOS Swift
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") {
                // TODO: Add network call here
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(8)

            if isLoading {
                ProgressView()
            }

            Text(resultText)
                .padding()
                .multilineTextAlignment(.center)
        }
        .padding()
    }
}

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

Final Result
Completed Screen
-------------------------
| Network Call Example   |
|-----------------------|
| [Fetch Data]          |
|                       |
| Loading...            |
|                       |
-------------------------

After success:
-------------------------
| Network Call Example   |
|-----------------------|
| [Fetch Data]          |
|                       |
| sunt aut facere repellat|
| provident occaecati   |
| excepturi optio       |
-------------------------
User taps 'Fetch Data' button.
Loading spinner appears while fetching.
On success, the post title text appears below the button.
On failure, an error message appears instead.
Stretch Goal
Add retry functionality: show a 'Retry' button when an error occurs to try fetching again.
💡 Hint
Use a state variable to track error state and conditionally show the Retry button that calls fetchData() again.

Practice

(1/5)
1. What is the main purpose of the error parameter in a network call's completion handler in Swift?
easy
A. To update the UI directly from the background thread
B. To store the data returned from the server
C. To specify the URL of the network request
D. To check if the network request failed and handle the failure

Solution

  1. Step 1: Understand the role of the error parameter

    The error parameter indicates if something went wrong during the network request. Developers check this parameter to detect failures and respond appropriately, like showing an alert.
  2. Final Answer:

    To check if the network request failed and handle the failure -> Option D
  3. Quick Check:

    Error parameter = check failure [OK]
Hint: Error parameter signals failure in network calls [OK]
Common Mistakes:
  • Confusing error with data parameter
  • Trying to update UI directly from background thread
  • Ignoring error and assuming success
2. Which of the following is the correct syntax to check for an error in a Swift network call completion handler?
easy
A. if error == nil { print("Error occurred") }
B. if error != nil { print("Error occurred") }
C. if error = nil { print("Error occurred") }
D. if error != false { print("Error occurred") }

Solution

  1. Step 1: Recall error checking syntax in Swift

    To check if an error exists, use if error != nil. Using != nil means an error was found, so handle it.
  2. Final Answer:

    if error != nil { print("Error occurred") } -> Option B
  3. Quick Check:

    Check error with != nil [OK]
Hint: Use 'if error != nil' to detect errors [OK]
Common Mistakes:
  • Using assignment '=' instead of comparison '=='
  • Checking error == nil to detect error (wrong logic)
  • Comparing error to false instead of nil
3. Consider this Swift code snippet for a network call:
URLSession.shared.dataTask(with: url) { data, response, error in
  if let error = error {
    print("Error: \(error.localizedDescription)")
  } else {
    print("Success")
  }
}.resume()
What will be printed if the network request fails due to no internet connection?
medium
A. Error: The Internet connection appears to be offline.
B. No output
C. Success
D. Crash due to unwrapped nil

Solution

  1. Step 1: Trace the code on network failure

    The code uses optional binding if let error = error which succeeds when error is not nil, printing the localized description like "The Internet connection appears to be offline." for no internet.
  2. Final Answer:

    Error: The Internet connection appears to be offline. -> Option A
  3. Quick Check:

    Error prints localizedDescription [OK]
Hint: Error prints message; success prints 'Success' [OK]
Common Mistakes:
  • Assuming success prints even on error
  • Expecting crash from optional binding
  • Ignoring error and printing nothing
4. This Swift code attempts to handle a network error but has a logic error:
URLSession.shared.dataTask(with: url) { data, response, error in
  if error == nil {
    print("No error")
  } else {
    print(error!.localizedDescription)
  }
}.resume()
What is the likely cause of the logic error?
medium
A. Not calling resume() on the data task
B. Force unwrapping error when it is nil
C. Using error == nil instead of error != nil
D. Printing error.localizedDescription without checking error

Solution

  1. Step 1: Analyze the logic and best practice

    The code checks if error == nil for success first, then handles error in else (safe unwrap). While functional, best practice is to check if error != nil first to explicitly handle failures before success.
  2. Final Answer:

    Using error == nil instead of error != nil -> Option C
  3. Quick Check:

    Error check logic reversed [OK]
Hint: Check error != nil to handle errors safely [OK]
Common Mistakes:
  • Reversing error check logic
  • Force unwrapping error without check
  • Not calling resume() on data task
5. You want to update a label's text after a network call completes. Which is the correct way to handle errors and update the UI safely in Swift?
URLSession.shared.dataTask(with: url) { data, response, error in
  // Handle error and update label
}
hard
A. Check if error != nil, then update label text inside DispatchQueue.main.async block
B. Update label text directly inside the completion handler without dispatching
C. Ignore error and update label text on background thread
D. Use try-catch inside the completion handler to update label

Solution

  1. Step 1: Handle threading and errors for UI updates

    Completion handlers run on background threads, so dispatch UI updates to main. First check if error != nil to handle failure (e.g., update label with error message), using DispatchQueue.main.async.
  2. Final Answer:

    Check if error != nil, then update label text inside DispatchQueue.main.async block -> Option A
  3. Quick Check:

    UI updates on main thread after error check [OK]
Hint: Always update UI on main thread after error check [OK]
Common Mistakes:
  • Updating UI on background thread causing crashes
  • Ignoring error and updating UI blindly
  • Using try-catch incorrectly for async callbacks
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