@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