NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SOLVED: SwiftUI, iOS15 Day 60 Challenge: retrieving data and loading to list

Forums > SwiftUI

Hi, I'm not getting my list, and I cannot work out why not as it does not appear to be showing me any errors:

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

struct User: Identifiable, Codable {

    let id: UUID
    var isActive: Bool
    let name: String
    var age: Int
    var company: String
    var email: String
    var address: String
    var about: String
    var registered: Date
    var tags: [String]
    var friends: [Friend]

}

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

    func loadData() async {
        guard !users.isEmpty else {
            return
        }

        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)

            if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
                users = decodedResponse.users

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

    }

    var body: some View {
        NavigationView {
            List(users) {user in
                HStack {
                    Text(user.name)
                        //.font(.body)

                    Text(user.isActive ? "Active" : "Unavailable")
                        //.font(.headline)
                }
            }
            .task {
                await loadData()
            }
            .navigationTitle("FriendsApp")

        }
    }
}

Help appreciated! Thank you.

1      

Change this:

if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
    users = decodedResponse.users
}

to this:

do {
    let decodedResponse = try JSONDecoder().decode(Response.self, from: data)
    users = decodedResponse.users
} catch {
    print(error)
}

and you'll actually get errors so you can start figuring out what's wrong. Using try? converts any error into nil and swallows it up so that you don't see it.

1      

@roosterboy, thanks for your help.

I ended up getting rid of the Response struct, and adding in the date decoding strategy (which I had interpreted in the text that it was so common it was just done automatically, and not that there was the .iso8601 that you could use), and using:

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
users = try decoder.decode([User].self, from: data)

1      

Hi @DantonCorbel! I have the same problem and I'm not getting my list. I think it is for the date decoding strategy but I can't implement this code

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
users = try decoder.decode([User].self, from: data)

I don't know where to put it. Any help? Thanks!

   

  1. @CacereLucas it has been a while since I did this - but I replaced the 'if let' in my 'ContentView: View' struct, in the 'loadData()' function. Any help?

   

Hacking with Swift is sponsored by MadMachine

SPONSORED Want to explore your Swift skill outside of the Apple world? Join the MadMachine community and start to program microcontrollers in Swift.

Get it now

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.