Search code examples
swiftuipublishobservableobjectobservedobject

Passing Decoded JSON Data to SwiftUI ContentView


API call and JSON decoding are working fine, as I can print to console any item from the JSON data set without a problem.

Here's API call and test print:

import Foundation
import SwiftUI
import Combine

class APICall : ObservableObject {

    @Published var summary: Summary?

        init () {
            pullSummary()
        }

    func pullSummary() {
        let urlCall = URL(string: "https://api.covid19api.com/summary")
        guard urlCall != nil else {
            print("Error reaching API")
            return
        }
        let session = URLSession.shared
        let dataTask = session.dataTask(with: urlCall!) { (data, response, error) in
            if error == nil && data != nil {
                let decoder = JSONDecoder()
                do {
                    let summary = try decoder.decode(Summary.self, from: data!)
                    print(summary.byCountry[40].cntry as Any)
                    DispatchQueue.main.async {
                        self.summary = summary
                    }
                }
                catch {
                    print("Server busy, try again in 5 min.")
                }
            }
        }
        dataTask.resume()
    }
}

And here is the structure of the "Summary" data model used for the decoding and data object structure:

import Foundation

struct Summary: Decodable {
    let global: Global
    let byCountry: [ByCountry]
    let date: String

    enum CodingKeys: String, CodingKey {
        case global = "Global"
        case byCountry = "Countries"
        case date = "Date"
    }

    struct Global: Decodable {
        let globalNC: Int
        let globalTC: Int
        let globalND: Int
        let globalTD: Int
        let globalNR: Int
        let globalTR: Int

        enum CodingKeys: String, CodingKey {
            case globalNC = "NewConfirmed"
            case globalTC = "TotalConfirmed"
            case globalND = "NewDeaths"
            case globalTD = "TotalDeaths"
            case globalNR = "NewRecovered"
            case globalTR = "TotalRecovered"
        }
    }

    struct ByCountry: Decodable {
        let cntry: String?
        let ccode: String
        let slug: String
        let cntryNC: Int
        let cntryTC: Int
        let cntryND: Int
        let cntryTD: Int
        let cntryNR: Int
        let cntryTR: Int
        let date: String

        enum CodingKeys: String, CodingKey {
            case cntry = "Country"
            case ccode = "CountryCode"
            case slug = "Slug"
            case cntryNC = "NewConfirmed"
            case cntryTC = "TotalConfirmed"
            case cntryND = "NewDeaths"
            case cntryTD = "TotalDeaths"
            case cntryNR = "NewRecovered"
            case cntryTR = "TotalRecovered"
            case date = "Date"
        }
    }
}

As shown, the results of the API call and JSON decode are published as required using ObserveableObject and @Published.

Over in the ContentView, I have followed the ObservedObject rules and only want to display on the UI a data point from the JSON data to confirm it's working:

import SwiftUI
import Foundation
import Combine

struct ContentView: View {

    @ObservedObject var summary = APICall()

    var body: some View {

        Text($summary.date)

        .onAppear {
            self.summary.pullSummary()
        }
    }

    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }
}

BUT... I get these 2 errors at the Text display line, 1) Initializer 'init(_:)' requires that 'Binding<Subject>' conform to 'StringProtocol' and 2) Value of type 'ObservedObject<APICall>.Wrapper' has no dynamic member 'date' using the key path from root type 'APICall'.

I am guessing the 2nd error is the root cause of the problem, indicating the data is not being passed into the ContentView correctly.

I appreciate any suggestions.

Thanks.


Solution

  • It is messed view model with internal property

    struct ContentView: View {
    
        @ObservedObject var viewModel = APICall()
    
        var body: some View {
    
            Text(viewModel.summary?.date ?? "Loading...") // << no $ sign !!!
    
            .onAppear {
                self.viewModel.pullSummary()
            }
        }
    }