I am using the following code in Swift Playground
import Foundation
struct PlayerInfo: Decodable{
var PlayerID: String = ""
var FirstName: String = ""
var LastName: String = ""
}
var rosterRequest = PlayerRequest()
rosterRequest.loadPlayers()
class PlayerRequest{
var players: [PlayerInfo] = []
func loadPlayers(){
guard let url = URL(string: "https://api.sportsdata.io/v3/nba/scores/json/Players?key=<key>") else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let mydata = data {
print(mydata)
if let players = try? JSONDecoder().decode([PlayerInfo].self, from: mydata){
DispatchQueue.main.async {
for player in players{
print(player.LastName)
}
}
return
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}
}.resume()
}
}
I know I get the data because it prints the length but when it come to parsing the data it fails.
Any help would be greatly appreciated.
When I run the request through Rested I get:
[
{
"PlayerID": 20000441,
"SportsDataID": "",
"Status": "Active",
...
},
{
"PlayerID": 20000442,
"SportsDataID": "",
"Status": "Active",
...
}
...
]
FirstNameandLastNamekeys? Or have you omitted them? Anyway, don't print thelocalizedDescriptionor the error.print(error)if you actually want to know what went wrong.