Skip to content

Instantly share code, notes, and snippets.

@fipso
Created July 31, 2021 12:00
Show Gist options
  • Save fipso/412f6b8d301e3cd87da0a92dc81b920c to your computer and use it in GitHub Desktop.
Save fipso/412f6b8d301e3cd87da0a92dc81b920c to your computer and use it in GitHub Desktop.
import Foundation
import FoundationNetworking
var countries = [Country]()
// MARK: - Summary
struct Summary: Codable {
let global: Global
let countries: [Country]
let date: String
enum CodingKeys: String, CodingKey {
case global = "Global"
case countries = "Countries"
case date = "Date"
}
}
// MARK: - Country
struct Country: Codable {
let country, countryCode, slug: String
let newConfirmed, totalConfirmed, newDeaths, totalDeaths: Int
let newRecovered, totalRecovered: Int
let date: String
enum CodingKeys: String, CodingKey {
case country = "Country"
case countryCode = "CountryCode"
case slug = "Slug"
case newConfirmed = "NewConfirmed"
case totalConfirmed = "TotalConfirmed"
case newDeaths = "NewDeaths"
case totalDeaths = "TotalDeaths"
case newRecovered = "NewRecovered"
case totalRecovered = "TotalRecovered"
case date = "Date"
}
}
// MARK: - Global
struct Global: Codable {
let newConfirmed, totalConfirmed, newDeaths, totalDeaths: Int
let newRecovered, totalRecovered: Int
enum CodingKeys: String, CodingKey {
case newConfirmed = "NewConfirmed"
case totalConfirmed = "TotalConfirmed"
case newDeaths = "NewDeaths"
case totalDeaths = "TotalDeaths"
case newRecovered = "NewRecovered"
case totalRecovered = "TotalRecovered"
}
}
//For local testing on linux (program exits before request callback otherwise)
let semaphore = DispatchSemaphore(value: 0)
let session = URLSession.shared
if let url = URL(string: "https://api.covid19api.com/summary") {
session.dataTask(with: url) {
jsonData, response, error in
if let jsonData = jsonData {
do {
let covidSummary = try JSONDecoder().decode(Summary.self, from: jsonData)
countries = covidSummary.countries
print(countries)
}
catch let error {
print(error)
}
semaphore.signal()
}
}.resume()
}
semaphore.wait()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment