Newbie here. How can i access the country id? and how do i access an array of objects? is there something i am missing? I do not know what to do here. I tried accessing with the index to get the country id from the json format but it keeps giving this error = https://ibb.co/6rN0gXr .
Anything else I should add to the parsing?
import UIKit
class ViewController: UIViewController {
let weatherURL = "https://dataservice.accuweather.com/locations/v1/cities/search?apikey=&q=aydın"
override func viewDidLoad() {
super.viewDidLoad()
fetchWeather()
}
func fetchWeather() {
// Create a URL
if let url = URL(string: weatherURL) {
// Create a URL Session
let session = URLSession(configuration: .default)
// Give the session a Task
let task = session.dataTask(with: url) { (data, response, error) in
if let safeData = data {
let dataString = String(data: safeData, encoding: .utf8)
self.parseJSON(weatherData: safeData)
// print(dataString.0.1)
}
}
// Start the task
task.resume()
}
}
struct LocationData: Decodable {
let country: Country
struct Country: Decodable {
let id: String
}
}
func parseJSON(weatherData: Data) {
do {
let decoder = JSONDecoder()
let decodedData = try decoder.decode([LocationData].self, from: weatherData)
let id = LocationData[0].country.ID
print(id)
} catch {
print(error)
}
}
}
>Solution :
You seems to have a json decoding error regarding country. Your data models must match the json data. For example using CodingKeys, such as:
struct LocationData: Decodable {
let country: Country
enum CodingKeys: String, CodingKey {
case country = "Country" // <--- here
}
}
struct Country: Decodable {
let id: String
enum CodingKeys: String, CodingKey {
case id = "ID" // <--- here
}
}