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

SOLVED: Error Fetching Json Covid

Forums > SwiftUI


import SwiftUI

struct Covid: Decodable{
    public var results : [Resultados]
}

struct Resultados: Codable, Hashable {
    public var city : String
}

class FetchCovid: ObservableObject {
  // 1.
  @Published var covids = [Resultados]()

    init() {
        let url = URL(string: "https://api.brasil.io/v1/dataset/covid19/caso/data/?format=json")!

        // 2.
        URLSession.shared.dataTask(with: url) {(data, response, error) in
            do {
                if let todoData = data {
                    // 3.
                    let decodedData = try JSONDecoder().decode([Resultados].self, from: todoData)
                    DispatchQueue.main.async {
                        self.covids = decodedData
                    }
                } else {
                    print("Nada encontrado")
                }
            } catch {
                print("Erro")
            }
        }.resume()
    }
}

struct ContentView: View {
    @ObservedObject var fetch = FetchCovid()

    var body: some View {
        VStack {
            Text("Listagem Covid")
                .padding()

            VStack{
                List(fetch.covids, id:\.self) { item in
                    Text(String(item.city))
                }
            }

            Spacer()
        }

    }
}

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

I Want to search in a specific city, how I can do it? Why my code dont work?

2      

Data require autentication.

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.