LAST CHANCE: Save 50% on all my Swift books and bundles! >>

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 Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.