UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

JSON not decoding

Forums > SwiftUI

I have trying to get some info from a website and using the following code. I get the data back but it does not decode

struct ResultsView: View {
    @State private var results = [Result]()

    var busId: String = "386"

     let appId = "" // giving app_id
    let appKey = "" // giving app_key

    var body: some View {
        List(results, id: \.lastUpdate) { item in
            VStack(alignment: .leading) {
                Text(item.description)
            }
        }
        .onAppear(perform: loadData)

    }

    func loadData() {
        guard let url = URL(string: "https://api.tfl.gov.uk/Line/\(busId)/Disruption?app_id=\(appId)&app_key=\(appKey)") else {
            print("Invalid URL")
            return
        }

        let request = URLRequest(url: url)

        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
                    DispatchQueue.main.async {
                        self.results = decodedResponse.results
                    }
                    return
                }
            }
            print("Fetch failed: \(error?.localizedDescription ?? "Unknown Error")")
        }.resume()
    }
}

Have these structs

struct Response: Codable {
    var results: [Result]
}

struct Result: Codable {
    var lastUpdate: String
    var description: String
}

Any idea what I have done wrong?

3      

It might help if you could post your JSON response so we can see if you have set up your Codable structs properly

3      

Please bear in mind that this is a link to live site and could change

https://api.tfl.gov.uk/Line/246/Disruption

this is what the response looks

[{"$type":"Tfl.Api.Presentation.Entities.Disruption, Tfl.Api.Presentation.Entities","category":"RealTime","type":"lineInfo","categoryDescription":"RealTime","description":"CHANGES TO ROUTE 246: Until further notice, the route will not operate between Westerham and Chartwell due to the closure of Chartwell House. All journeys will operate between Bromley North and Westerham only.","created":"2020-03-23T09:30:00Z","lastUpdate":"2020-03-23T09:32:00Z","affectedRoutes":[],"affectedStops":[]}]

or visit TfL with complete brakdown

https://api.tfl.gov.uk/swagger/ui/index.html?url=/swagger/docs/v1#!/Line/Line_Disruption

3      

@StewartLynch Did that help?

3      

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 April 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.