I'm parsing an an XML file which gives me an array of ParkingGarage
.
struct ParkGarage: Identifiable {
var id = UUID()
var title: String = ""
var address: String = ""
var link: String = ""
var description: String = ""
var pubDate: String = ""
var guid: String = ""
var dcDate: String = ""
var state: String = ""
var freeSpaces: Int = 0
var coordinate: CLLocationCoordinate2D = CLLocationCoordinate2D()
}
My problem is, that I have to get the coordinates
of each garage after it has been parsed since I'm not getting that information of the XML.
This is my loadData
function:
func loadData() {
lazy var geocoder = CLGeocoder()
var invalid: Bool = false
let xmlParser = GarageParser()
guard let url = URL(string: "https://www.my-url") else {
print("Your API end point is Invalid")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error ?? "Unknown error")
return
}
var fetchedGarages = xmlParser.parseGarages(data: data)
fetchedGarages = self.setAllNewFields(garages: fetchedGarages)
for (index, garage) in fetchedGarages.enumerated() {
geocoder.geocodeAddressString(garage.address + ", Zürich") { placemarks, error in
if let error = error {
DispatchQueue.main.async {
invalid = true
}
print(error.localizedDescription)
}
guard let placemark = placemarks?.first else {
return
}
guard let lat = placemark.location?.coordinate.latitude else{return}
guard let lon = placemark.location?.coordinate.longitude else{return}
let coords = CLLocationCoordinate2DMake(lat, lon)
fetchedGarages[index].coordinate = coords
}
}
DispatchQueue.main.async {
self.garages = fetchedGarages
}
}
}
My Problem now is, that it is not awaited until all coordinates are fetched.
Is there a good way to do so?
I'm new to swift, I'm happy for all the input I can get.