https://maps.googleapis.com/maps/api/place/autocomplete/json?input=station%20bab%20saadoun&key=GOOGLE_API_KEY&components=country:TN
func googleAutocomplete(for query: String, completion: @escaping ([GooglePlaces]) -> Void) {
let apiKey = GoogleMapAPIs.shared.apiKey
let baseURL = "https://maps.googleapis.com/maps/api/place/autocomplete/json"
guard let url = URL(string: "\(baseURL)?input=\(query)&key=\(apiKey)&components=country:TN") else {
print("Invalid URL")
completion([])
return
}
print(url)
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("Error fetching data: \(error.localizedDescription)")
completion([])
return
}
guard let data = data else {
print("No data received")
completion([])
return
}
do {
let decodedResponse = try JSONDecoder().decode(GooglePlacesResponse.self, from: data)
completion(decodedResponse.predictions)
} catch {
print("Decoding error: \(error)")
completion([])
}
}
task.resume()
}
struct GooglePlaces: Codable {
let title: String?
let region: StructuredFormatting?
let placeID: String?
enum CodingKeys: String, CodingKey {
case title = "description"
case region = "structured_formatting"
case placeID = "place_id"
}
}
struct StructuredFormatting: Codable {
let main_text: String
let secondary_text: String?
}
struct GooglePlacesResponse: Codable {
let predictions: [GooglePlaces]
}
Error fetching data: The network connection was lost.
Topic:
Developer Tools & Services
SubTopic:
Xcode