Search code examples
swiftcallbackgoogle-places-apigoogle-maps-sdk-ios

placesClient - properly use sharedClient method?


placesClient gives an error of holding a nil value, after reading through the google places documentation I read this statement:

This class should be accessed through the [GMSPlacesClient sharedClient] method.

I am wondering how to implement the sharedClient method in order to run a search based on the placesID for the information on the given place?

var placesClient: GMSPlacesClient!

func lookUpPlaceID() {
    let placeID = "ChIJPXw5JDZM6IAR4rTXaFQDGys"

    //What value should placesClient be holding if not GMSPlacesClient in order to run the search based on the placeID?

    self.placesClient.lookUpPlaceID(placeID, callback: { (place, error) -> Void in

    if let error = error {
            print("lookup place id query error: \(error.localizedDescription)")
            return
        }

        if let place = place {
            print("Place name \(place.name)")
            print("Place address \(place.formattedAddress)")
            print("Place placeID \(place.placeID)")
            print("Place attributions \(place.attributions)")
        } else {
            print("No place details for \(placeID)")
        }
    })


}

Solution

  • sharedClient is class method in Objective C. In Swift you treat it like a Type Method. So instead of assigning placesClient to the GMSPlacesClient type, assign it to the result of the sharedClient type method:

    let placesClient = GMSPlacesClient.sharedClient()
    

    placesClient will now hold an instance of GMSPlacesClient (a shared instance, later calls to sharedClient will return the same instance if it hasn't been garbage collected), rather than holding the type as your original code did.