2

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",
        ...
    }
...
]
1
  • 1
    Your JSON doesn't seem to have FirstName and LastName keys? Or have you omitted them? Anyway, don't print the localizedDescription or the error. print(error) if you actually want to know what went wrong. Commented Nov 6, 2020 at 0:45

1 Answer 1

1

I figured it out. PlayerID is an Int and I had it defined as a String

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.