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

SOLVED: Day 60: Date property blocking my list view

Forums > 100 Days of SwiftUI

I'm facing some problems with this project. I'm able to show everything if i give the type "String" to my "registered" property, but if i change the type to "Date" the list stops showing but no error gets triggered. Don't know what to do...

My code:

import SwiftUI

struct ContentView: View {

   @State private var users = [User]()

    var body: some View {
        NavigationView {
            List (users, id: \.id) { user in
                NavigationLink {
                    UserDetailView(user: user)
                } label: {
                    HStack {
                        VStack (alignment: .leading) {
                            Text (user.name)
                                .font(.headline)
                            Text (user.email)
                                .font(.subheadline)
                        }

                        Spacer()

                        Image(systemName: "circle.fill")
                            .foregroundColor(user.isActive ? .green : .red)
                    }
                }
            }
            .navigationTitle("Profiles")
            .task {
                await users.isEmpty ? loadData() : nil
            }
        }
    }

    func loadData() async {

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

        JSONDecoder().dateDecodingStrategy = .iso8601

        do {

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

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

        } catch {

            print ("Invalid data")

        }

    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
import Foundation

struct User: Codable, Identifiable {

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

    var formattedDate: String {
        registered.formatted(date: .abbreviated, time: .omitted)
    }

}

2      

Hi! The issue is that in your code you have created two instances of Decoder. One with decoding strategy and default one. The latter you use in your do - catch block.

You need to change it as follows:

        let decoder = JSONDecoder() // you create your decoder
        decoder.dateDecodingStrategy = .iso8601 // assign decoding strategy

        do {

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

            if let decodedResponse = try? decoder.decode([User].self, from: data) { // use created decoder
                users = decodedResponse
            }

        } catch {

            print ("Invalid data")

        }

in your code you have set it up as:

JSONDecoder().dateDecodingStrategy = .iso8601 // instance one of decoder

        do {

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

            if let decodedResponse = try? JSONDecoder().decode([User].self, from: data) { // instance two of decoder which is absolutely new object
                users = decodedResponse
            }

        } catch {

            print ("Invalid data")

        }

3      

Thank you very much. Problem fixed.

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.