0
0
iOS Swiftmobile~20 mins

URLSession basics in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Simple Fetch Screen
This screen fetches text data from a URL and shows it on screen.
Target UI
-------------------------
| Simple Fetch Screen    |
|-----------------------|
| [Fetch Data]          |
|                       |
|                       |
|                       |
|                       |
|                       |
|                       |
-------------------------
Add a button labeled 'Fetch Data'.
When tapped, fetch text from https://www.example.com using URLSession.
Show the fetched text below the button.
Show a loading indicator while fetching.
Show an error message if fetch fails.
Starter Code
iOS Swift
import SwiftUI

struct SimpleFetchScreen: View {
    @State private var fetchedText = ""
    @State private var isLoading = false
    @State private var errorMessage = ""

    var body: some View {
        VStack(spacing: 20) {
            Button("Fetch Data") {
                // TODO: Add fetch code here
            }
            if isLoading {
                ProgressView()
            }
            if !errorMessage.isEmpty {
                Text(errorMessage).foregroundColor(.red)
            }
            ScrollView {
                Text(fetchedText)
                    .padding()
            }
            Spacer()
        }
        .padding()
        .navigationTitle("Simple Fetch Screen")
    }
}

struct SimpleFetchScreen_Previews: PreviewProvider {
    static var previews: some View {
        SimpleFetchScreen()
    }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
iOS Swift
import SwiftUI

struct SimpleFetchScreen: View {
    @State private var fetchedText = ""
    @State private var isLoading = false
    @State private var errorMessage = ""

    var body: some View {
        VStack(spacing: 20) {
            Button("Fetch Data") {
                fetchData()
            }
            if isLoading {
                ProgressView()
            }
            if !errorMessage.isEmpty {
                Text(errorMessage).foregroundColor(.red)
            }
            ScrollView {
                Text(fetchedText)
                    .padding()
            }
            Spacer()
        }
        .padding()
        .navigationTitle("Simple Fetch Screen")
    }

    func fetchData() {
        isLoading = true
        errorMessage = ""
        fetchedText = ""
        guard let url = URL(string: "https://www.example.com") else {
            errorMessage = "Invalid URL."
            isLoading = false
            return
        }
        URLSession.shared.dataTask(with: url) { data, response, error in
            DispatchQueue.main.async {
                isLoading = false
                if let error = error {
                    errorMessage = "Error: \(error.localizedDescription)"
                    return
                }
                guard let data = data, let text = String(data: data, encoding: .utf8) else {
                    errorMessage = "Failed to load data."
                    return
                }
                fetchedText = text
            }
        }.resume()
    }
}

struct SimpleFetchScreen_Previews: PreviewProvider {
    static var previews: some View {
        SimpleFetchScreen()
    }
}

This solution uses URLSession.shared.dataTask to fetch data from the given URL asynchronously. We set isLoading to true before starting the fetch to show a loading spinner. When the fetch completes, we switch back to the main thread using DispatchQueue.main.async to update the UI states safely.

If there is an error, we show a red error message. If the data is successfully fetched, we convert it to a string and display it below the button. This simple pattern is the foundation for network calls in iOS apps.

Final Result
Completed Screen
-------------------------
| Simple Fetch Screen    |
|-----------------------|
| [Fetch Data]          |
|                       |
|    (loading spinner)   |
|                       |
| <fetched text shown>  |
|                       |
|                       |
-------------------------
User taps 'Fetch Data' button.
Loading spinner appears while data loads.
Fetched text from https://www.example.com appears below the button.
If fetch fails, a red error message appears instead.
Stretch Goal
Add a refresh button in the navigation bar to fetch data again.
💡 Hint
Use .toolbar modifier with a Button that calls fetchData() when tapped.