UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 60 challenge list not displaying

Forums > 100 Days of SwiftUI

I am trying to complete the day 60 challenge on the 100 days of SwiftUI course but have ran into a problem.

XCode is not showing any errors in my code but the simulator and preview aren't displaying the list that i inputed - just a white screen with a navigation title. I have spent hours trying to figure out this problem, watching numerous videos from earlier in the course and looking at other solutions people have used but still cannot figure out what is going wrong.

Does anyone have any solutions, tips or links to useful videos for this problem? And, it would be much appreciated if somebody could try my code on their mac to see if its just my XCode playing up.

Here is my code:

ContentView.swift

import SwiftUI

struct ContentView: View {
    @State private var users = [User]()

    var body: some View {
        NavigationStack {
            List {
                ForEach(users, id: \.name) { user in
                    Text(user.name)
                }
            }
            .task {
                await loadData()
            }

            .navigationTitle("iExpense")
        }

    }

    func loadData() async {
        guard let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json") else {
            print("Invalid URL")
            return
        }

        do {
            let (data, _) = try await URLSession.shared.data(from: url)

            do {
                let decodedResponse = try JSONDecoder().decode([User].self, from: data)
                var users = decodedResponse
                return
            } catch {
                print("response failed")
            }

        } catch {
            print("Invalid data")
        }
    }

}

#Preview {
    ContentView()
}

User.swift

import Foundation

struct User: Identifiable, Codable {    
    var id: UUID
    var isActive: Bool
    var name: String
    var age: Int
    var company: String?
    var email: String
    var address: String
    var about: String
    var registered: Date

Friend.swift

import Foundation

struct Friend: Identifiable, Codable {
    var id: UUID
    var name: String
}

1      

@oscar is trying to track down a bug.....

I have spent hours trying to figure out this problem, watching numerous videos
from earlier in the course and looking at other solutions people have used
but still cannot figure out what is going wrong.

Welcome to Hacking with SwiftUI

You are making mistakes? Good job! That is part of the learning process.

Help yourself now by learning some debugging techniques. One of the most basic techniques is to sprinkle your code with print statements. Later, you should look into assert() statements!

See -> Assert Yourself

But start with print().

Comment your code!

Next, it's useful if we know that you understand what you're writing. So take a moment to add comments documenting your understanding. If you're not grokking a concept, we can steer you in the right direction.

Your code

I copied your code, added several print statements and found your error in 5 minutes. HINT: It's a scope issue. Something in or out of scope.

Add a warning light to your NavigationStack! This is one of those annoying lights on your car's dashboard. Just put it there whilst you debug your code. What is the output? Is the number what you expected?

NavigationStack {
            Text("User Count \(users.count)")  // <-- ADD A WARNING LIGHT
            List {
                ForEach(users) { user in
                    Text(user.name)
                }
            }
            .task { await loadData() }
            .navigationTitle("Friends")
        }

Depending on the value in your Warning Light, you may want to look deeper into your code.

func loadData() async {
    guard let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json") else {
        print("Invalid URL")
        return
    }
    // =============== Passed the Guard
    // What do you expect at this point?
    print("URL is: \(url.absoluteString)") // <-- What data do you get here?
    assert( !url.absoluteString.isEmpty, "Error with your URL.") // <-- What does this do? 
        do {
            let (data, _) = try await URLSession.shared.data(from: url) // <-- underscore HIDES the error. is this what you want?
            print("Data size: \(data.count)") // <-- How many bytes were returned ? Is this the right amount?

            // =========== KEEP ADDING PRINT STATEMENT TO VERIFY YOUR ASSUMPTIONS ===========
            do {
                let decodedResponse = try JSONDecoder().decode([User].self, from: data)
                var users = decodedResponse
                return
            } catch {
                print("response failed")
            }

        } catch {
            print("Invalid data")
        }
    }

Keep Coding

1      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.