I am not sure of the cause but think it might be to do with the date
Try using
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
I have included my project on this for reference
struct ContentView: View {
@State private var users = [User]()
var body: some View {
NavigationView {
List {
ForEach(users, id: \.id) { user in
UserRow(user: user)
}
}
.navigationTitle("User Profiles")
}
.onAppear(perform: loadData)
}
func loadData() {
guard let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json") else {
fatalError("Invalid URL")
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
if let data = data {
if let decodedUsers = try? decoder.decode([User].self, from: data) {
DispatchQueue.main.async {
users = decodedUsers
}
return
}
}
print("Fetch failed \(error?.localizedDescription ?? "Unknown Error")")
}.resume()
}
}
UserRow file
import SwiftUI
struct UserRow: View {
let user: User
var body: some View {
VStack(alignment: .leading) {
HStack {
Text(user.name)
.font(.title3)
.bold()
Spacer()
Text("Joined: \(user.registered, style: .date)")
.foregroundColor(.secondary)
}
Text(user.company)
}
}
}
struct UserRow_Previews: PreviewProvider {
static var previews: some View {
UserRow(user: User.example)
.previewLayout(.sizeThatFits)
}
}
User file
import Foundation
struct User: Identifiable, Decodable {
let id: String
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]
struct Friend: Identifiable, Decodable {
let id: String
let name: String
}
#if DEBUG
// show in preview set up only
static let example = User(
id: "0",
isActive: true,
name: "Test Name",
age: 99,
company: "Test.inc",
email: "test@test.com",
address: "1 Test drive", about: "Occaecat consequat elit aliquip magna laboris dolore laboris sunt officia adipisicing reprehenderit sunt. Do in proident consectetur labore. Laboris pariatur quis incididunt nostrud labore ad cillum veniam ipsum ullamco. Dolore laborum commodo veniam nisi. Eu ullamco cillum ex nostrud fugiat eu consequat enim cupidatat. Non incididunt fugiat cupidatat reprehenderit nostrud eiusmod eu sit minim do amet qui cupidatat. Elit aliquip nisi ea veniam proident dolore exercitation irure est deserunt.\r\n", registered: Date(), tags: ["cillum"], friends: [])
#endif
}