0
0
iOS Swiftmobile~20 mins

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

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