I'm trying to start the day 60 challenge but I am stuck.
For now, I am just trying to keep it simple, to make sure that I am decoding the data from the URL successfully, but so far it isn't working.
It looks like the data is being downloaded just fine, but the problem is occurring when I try to decode the data into instances of the User struct that I have created.
The data being used in this project can be found at this link https://www.hackingwithswift.com/samples/friendface.json
I'm not sure if I have not set up the the types of my properties for the User or Friend structs correctly, or if the problem is coming from the Date not being formatted correctly, or if it is something else. If somebody could point me in the right direction, it would be much appreciated.
This is what I have so far, and it is printing "Unknown Error" as shown at the bottom of ContentView
import SwiftUI
struct ContentView: View {
@State private var users = [User]()
var body: some View {
NavigationView {
List(users) { user in
Text("\(user.name)")
}
.onAppear(perform: loadUserData)
}
}
func loadUserData() {
guard let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json") else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let userData = data {
let userDecoder = JSONDecoder()
let registrationDateFormatter = DateFormatter()
registrationDateFormatter.dateFormat = "y-MM-dd"
userDecoder.dateDecodingStrategy = .formatted(registrationDateFormatter)
if let decodedUsers = try? userDecoder.decode([User].self, from: userData) {
DispatchQueue.main.async {
users = decodedUsers
}
return
}
}
print("Fetch Failed: \(error?.localizedDescription ?? "Unknown Error")")
}.resume()
}
}
import Foundation
struct User: Codable, Identifiable {
var 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]
}
import Foundation
struct Friend: Codable, Identifiable {
var id: UUID
let name: String
}