I am trying to parse out the longitude and latitude of the London eye. My code is as follows
Here is my class:
struct Location: Decodable{
let location: String
let lat: Double
let long: Double
}
Here is my Function
func getData(){
let url = "URL FOR THE JSON"
let urlOBJ = URL(string: url)
URLSession.shared.dataTask(with: urlOBJ!){(data,response,errror) in
do{
let locations = try JSONDecoder().decode([Location].self, from: data!)
for x in locations{
print(x.lat)
}
}
catch{
print("We got an error")
}
}.resume()
Here is my JSON response:
{
"results" : [
{
"address_components" : [
{
"long_name" : "918",
"short_name" : "918",
"types" : [ "street_number" ]
},
{
"long_name" : "12th Street",
"short_name" : "12th St",
"types" : [ "route" ]
},
{
"long_name" : "New Westminster",
"short_name" : "New Westminster",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Greater Vancouver",
"short_name" : "Greater Vancouver",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "British Columbia",
"short_name" : "BC",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Canada",
"short_name" : "CA",
"types" : [ "country", "political" ]
},
{
"long_name" : "V3M 6B1",
"short_name" : "V3M 6B1",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "918 12th St, New Westminster, BC V3M 6B1, Canada",
"geometry" : {
"location" : {
"lat" : 49.2122785,
"lng" : -122.9368196
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 49.21362748029149,
"lng" : -122.9354706197085
},
"southwest" : {
"lat" : 49.21092951970849,
"lng" : -122.9381685802915
}
}
},
"place_id" : "ChIJt0rd0NB3hlQRWKnWCK79k1s",
"plus_code" : {
"compound_code" : "6367+W7 New Westminster, British Columbia, Canada",
"global_code" : "84XV6367+W7"
},
"types" : [ "doctor", "establishment", "health", "point_of_interest" ]
}
],
"status" : "OK"
}
I want to extract the location from the geometry section of the response but think that I have mis understood how to get there. Any help is welcome as I am new to this.
When I run this I am redirected to my error message so I think it is just not finding the longitude or latitude.
Please ask if you have any questions regarding my code.
"We got an error"in acatchblock when catching aCodableerror. Don't do that. Print the error:print(error).Codableerrors are extremely descriptive. They tell you exactly what's wrong.{}) which is not aLocation. There is a keystatusand a keyresults. The value for keyresultsis an array of another dictionary. This dictionary contains the keygeometryand this object contains the keylocation.