Created
July 14, 2020 02:42
-
-
Save satan87/5df72c2bd32a55a9d20cea07e13e65a9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import GooglePlaces | |
final class GooglePlaceService { | |
private var placesClient: GMSPlacesClient! | |
private var filter = GMSAutocompleteFilter() | |
// Map the Google Category to your own category | |
private let typesToDrink = ["bar", "cafe"] | |
private let typesToEat = ["meal_delivery", "meal_takeaway", "restaurant"] | |
init() { | |
// Initialization of the iOS SDK | |
placesClient = GMSPlacesClient.shared() | |
filter.type = .establishment | |
} | |
func retrieve(from: String, completionBlock: @escaping ([Place]) -> Void) { | |
var places = [Place]() | |
// AUTOCOMPLETE REQUEST | |
placesClient.findAutocompletePredictions( | |
fromQuery: from, | |
filter: filter, | |
sessionToken: nil) { (predictions: [GMSAutocompletePrediction]?, error: Error?) in | |
if let error = error { | |
print("GPT ERROR PLACE: An error occurred: \(error.localizedDescription)") | |
return | |
} | |
if let choices = predictions { | |
for choice in choices { | |
var place = Place() | |
place.name = choice.attributedPrimaryText.string | |
place.comment = choice.placeID | |
var address = Address() | |
address.street = choice.attributedSecondaryText?.string ?? "" | |
place.addresses.append(address) | |
places.append(place) | |
} | |
} | |
completionBlock(places) | |
} | |
} | |
// SECOND REQUEST - Necessary to retrieve Detail information | |
func retrieve(place placeId: String, completionBlock: @escaping (Place?) -> Void) { | |
// Define the fields you want in the response | |
let fields = GMSPlaceField(rawValue: | |
UInt(GMSPlaceField.name.rawValue) | |
| UInt(GMSPlaceField.placeID.rawValue) | |
| UInt(GMSPlaceField.addressComponents.rawValue) | |
| UInt(GMSPlaceField.formattedAddress.rawValue) | |
| UInt(GMSPlaceField.types.rawValue) | |
| UInt(GMSPlaceField.coordinate.rawValue) | |
)! | |
placesClient.fetchPlace( | |
fromPlaceID: placeId, | |
placeFields: fields, | |
sessionToken: nil, | |
callback: { (googlePlace: GMSPlace?, error: Error?) in | |
if let error = error { | |
print("GPT ERROR PLACE: An error occurred: \(error.localizedDescription)") | |
return | |
} | |
if let googlePlace = googlePlace, let name = googlePlace.name { | |
var place = Place() | |
place.name = name | |
//Address | |
var address = Address() | |
address.street = googlePlace.addressComponents?.first(where: {$0.types.contains("route")})?.name ?? "" | |
// handle the rest of the address | |
place.addresses.append(address) | |
completionBlock(place) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment