Migrating to the New Places SDK Client

The v.3.0.0 release of the Places SDK for iOS has been updated with new functionality. The current version of the Places SDK for iOS (v.2.7.0) is deprecated as of January 29, 2019, and will be turned off on July 29, 2019. In order to continue using the Places SDK for iOS, we recommend that you update your project to use v.3.0.0 as soon as possible.

This guide explains the changes, and shows you how to update your projects to use the new version of the Places SDK for iOS.

What's changed?

The Places SDK for iOS has changed in the following ways:

Update to the latest Places client library

A new client library is now available for the Places SDK for iOS. In order to use the new features, you must update your existing projects to use the v.3.0.0 client library.

  • To build a project using the Places SDK for iOS, you need version 9.0 or later of Xcode.
  • As of v.3.0.0, the minimum supported iOS version is iOS 9.

Take the following steps to update your project to use the latest version of the Places SDK for iOS:

  1. Open the Xcode project that you want to update.
  2. Ensure that your podfile contains the correct dependencies, and does not restrict to a specific version. It should look similar to this (include GoogleMaps only if your app uses the Place Picker):

    source 'https://github.com/CocoaPods/Specs.git'
    target 'YOUR_APPLICATION_TARGET_NAME_HERE' do
      pod 'GooglePlaces'
      pod 'GoogleMaps'
    end
    
  3. Open a terminal and go to the directory containing the Podfile.

  4. Run the pod update command. This will update the APIs specified in the Podfile to the latest version.

If you're creating a new project, follow the installation instructions.

New methods

This section shows you how to use the new methods that were introduced in the latest release.

The following new methods have been added:

These methods support the following new functionality:

  • Field masks are now supported for methods that return place details. You can use field masks to specify which types of place data to return (previously all available data would be returned).
  • Session tokens are now supported for Place Autocomplete.

Fetch a place by ID

fetchPlaceFromPlaceID: replaces both lookUpPlaceID: and lookUpPhotosForPlaceID:. Use fetchPlaceFromPlaceID: to get details about a particular place. fetchPlaceFromPlaceID: takes the following parameters:

  • A string containing a Place ID.
  • One or more GMSPlaceFields, specifying the data types to return.
  • A session token (optional, to be used if this call is made to conclude an autocomplete query.
  • A GMSPlaceResultCallback to handle the result (in this example the callback uses a closure).

The following code example shows calling fetchPlaceFromPlaceID:, and getting place details for the specified place:

Swift

// Specify the place data types to return.
let fields: GMSPlaceField = GMSPlaceField(rawValue:
  UInt(GMSPlaceField.name.rawValue) | UInt(GMSPlaceField.placeID.rawValue))!

// Create a new session token.
placesClient?.fetchPlace(fromPlaceID: "INSERT_PLACE_ID_HERE",
                         placeFields: fields,
                         sessionToken: token, callback: {
  (place: GMSPlace?, error: Error?) in
  if let error = error {
    print("An error occurred: \(error.localizedDescription)")
    return
  }

  if let place = place {
    print("The selected place is: \(String(describing: place.name)), \(String(describing: place.placeID))")
  }
})

Objective-C

NSString *placeId = @"INSERT_PLACE_ID_HERE";

// Specify the place data types to return.
GMSPlaceField fields = (GMSPlaceFieldName | GMSPlaceFieldPlaceID);

[_placesClient fetchPlaceFromPlaceID:placeId placeFields:fields sessionToken:nil callback:^(GMSPlace * _Nullable place, NSError * _Nullable error) {
  if (error != nil) {
    NSLog(@"An error occurred %@", [error localizedDescription]);
    return;
  }
  if (place != nil) {
    NSLog(@"The selected place is: %@", [place name]);
  }
}];

Fetch a place photo

The process for retrieving place photos has changed. You can get place photo metadata, including a bitmap and accompanying attribution text, by calling fetchPlaceFromPlaceId, and passing the GMSPlaceField.photos place field. The callback for getting the actual bitmap and attribution text has not changed (you still use loadPlacePhoto: to do this).

The following example shows how to get the bitmap and attribution text for the first place photo for a given place:

Swift

// Specify the place data types to return (in this case, just photos).
let fields: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.photos.rawValue))!

placesClient?.fetchPlace(fromPlaceID: "INSERT_PLACE_ID_HERE",
                         placeFields: fields,
                         sessionToken: nil, callback: {
  (place: GMSPlace?, error: Error?) in
  if let error = error {
    // TODO: Handle the error.
    print("An error occurred: \(error.localizedDescription)")
    return
  }
  if let place = place {
    // Get the metadata for the first photo.
    let photoMetadata: GMSPlacePhotoMetadata = place.photos![0]

    // Call loadPlacePhoto to display the bitmap and attribution.
    self.placesClient?.loadPlacePhoto(photoMetadata, callback: { (photo, error) -> Void in
      if let error = error {
        print("Error loading photo metadata: \(error.localizedDescription)")
        return
      } else {
        // Display the first image and its attributions.
        self.imageView?.image = photo;
        self.attributionTextView?.attributedText = photoMetadata.attributions;
      }
    })
  }
})

Objective-C

// Specify the place data types to return (in this case, just photos).
GMSPlaceField fields = (GMSPlaceFieldPhotos);

NSString *placeId = @"INSERT_PLACE_ID_HERE";

[_placesClient fetchPlaceFromPlaceID:placeId placeFields:fields sessionToken:nil callback:^(GMSPlace * _Nullable place, NSError * _Nullable error) {
  if (error != nil) {
    NSLog(@"An error occurred %@", [error localizedDescription]);
    return;
  }
  if (place != nil) {
    GMSPlacePhotoMetadata *photoMetadata = [place photos][0];
    [self->_placesClient loadPlacePhoto:photoMetadata callback:^(UIImage * _Nullable photo, NSError * _Nullable error) {
      if (error != nil) {
        NSLog(@"Error loading photo metadata: %@", [error localizedDescription]);
        return;
      } else {
        // Display the first image and its attributions.
        self->imageView.image = photo;
        self->lblText.attributedText = photoMetadata.attributions;
      }
    }];
  }
}];

Get the current location

findPlaceLikelihoodsFromCurrentLocationWithPlaceFields: takes the place of currentPlaceWithCallback:. Use findPlaceLikelihoodsFromCurrentLocationWithPlaceFields: to get the place that is closest to the location of the user's device.

findPlaceLikelihoodsFromCurrentLocationWithPlaceFields: takes the following parameters:

  • One or more GMSPlaceFields, specifying the data types to return.
  • A GMSPlaceLikelihoods callback to handle the result (in this example the callback uses a closure).

The following example shows calling findPlaceLikelihoodsFromCurrentLocationWithPlaceFields:, and getting a list of GMSPlaceLikelihoods.

Swift

// Specify the place data types to return.
let fields: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.name.rawValue) |
                                          UInt(GMSPlaceField.placeID.rawValue))!
placesClient?.findPlaceLikelihoodsFromCurrentLocation(withPlaceFields: fields, callback: {
  (placeLikelihoodList: Array<GMSPlaceLikelihood>?, error: Error?) in
  if let error = error {
    print("An error occurred: \(error.localizedDescription)")
    return
  }

  if let placeLikelihoodList = placeLikelihoodList {
    for likelihood in placeLikelihoodList {
      let place = likelihood.place
      print("Current Place name \(String(describing: place.name)) at likelihood \(likelihood.likelihood)")
      print("Current PlaceID \(String(describing: place.placeID))")
    }
  }
})

Objective-C

// Specify the place data types to return.
GMSPlaceField fields = (GMSPlaceFieldName | GMSPlaceFieldPlaceID);
[_placesClient findPlaceLikelihoodsFromCurrentLocationWithPlaceFields:fields callback:^(NSArray<GMSPlaceLikelihood *> * _Nullable likelihoods, NSError * _Nullable error) {
  if (error != nil) {
    NSLog(@"An error occurred %@", [error localizedDescription]);
    return;
  }
  if (likelihoods != nil) {
    for (GMSPlaceLikelihood *likelihood in likelihoods) {
      GMSPlace *place = likelihood.place;
      NSLog(@"Current place name: %@", place.name);
      NSLog(@"Place ID: %@", place.placeID);
    }
  }
}];

IMPORTANT! findPlaceLikelihoodsFromCurrentLocationWithPlaceFields: does not support the following fields:

  • GMSPlaceFieldAddressComponents
  • GMSPlaceFieldOpeningHours
  • GMSPlaceFieldPhoneNumber
  • GMSPlaceFieldWebsite

Find autocomplete predictions

findAutocompletePredictionsFromQuery: replaces autocompleteQuery:. Use findAutocompletePredictionsFromQuery: to return place predictions in response to user search queries.

The following example shows calling findAutocompletePredictionsFromQuery::

Swift

/**
 * Create a new session token. Be sure to use the same token for calling
 * findAutocompletePredictions, as well as the subsequent place details request.
 * This ensures that the user's query and selection are billed as a single session.
 */
let token: GMSAutocompleteSessionToken = GMSAutocompleteSessionToken.init()

// Create a type filter.
let filter = GMSAutocompleteFilter()
filter.type = .establishment

// Query string for testing.
let query: String = "cheesebu"

// Set the bounds to Honolulu, HI.
let neBoundsCorner = CLLocationCoordinate2D(latitude: 21.392919,
                                            longitude: -157.943280)
let swBoundsCorner = CLLocationCoordinate2D(latitude: 21.278330,
                                            longitude: -157.686202)
let bounds = GMSCoordinateBounds(coordinate: neBoundsCorner,
                                 coordinate: swBoundsCorner)

placesClient?.findAutocompletePredictions(fromQuery: query,
                                          bounds: bounds,
                                          boundsMode: GMSAutocompleteBoundsMode.bias,
                                          filter: filter,
                                          sessionToken: token,
                                          callback: { (results, error) in
    if let error = error {
      // TODO: Handle the error.
      print("Autocomplete error \(error)")
      return
    }
    if let results = results {
      for result in results {
        print("Result \(result.attributedFullText) with placeID \(result.placeID)")
      }
    }
})

Objective-C

/**
 * Create a new session token. Be sure to use the same token for calling
 * findAutocompletePredictionsFromQuery:, as well as the subsequent place details request.
 * This ensures that the user's query and selection are billed as a single session.
 */
GMSAutocompleteSessionToken *token = [[GMSAutocompleteSessionToken alloc] init];

// Create a type filter.
GMSAutocompleteFilter *_filter = [[GMSAutocompleteFilter alloc] init];
_filter.type = kGMSPlacesAutocompleteTypeFilterEstablishment;

// Set the bounds to Honolulu, HI.
CLLocationCoordinate2D neBoundsCorner = CLLocationCoordinate2DMake(21.392919, -157.943280);
CLLocationCoordinate2D swBoundsCorner = CLLocationCoordinate2DMake(21.278330, -157.686202);
GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] initWithCoordinate:neBoundsCorner
                                                                   coordinate:swBoundsCorner];

[_placesClient findAutocompletePredictionsFromQuery:@"cheesebu" bounds:bounds boundsMode:kGMSAutocompleteBoundsModeBias
filter:_filter sessionToken:token callback:^(NSArray<GMSAutocompletePrediction *> * _Nullable results, NSError * _Nullable error) {
  if (error != nil) {
    NSLog(@"An error occurred %@", [error localizedDescription]);
    return;
  }
  if (results != nil) {
    for (GMSAutocompletePrediction *result in results) {
      NSLog(@"Result %@ with PlaceID %@", result.attributedFullText, result.placeID);
    }
  }
}];

Session tokens

Session tokens group the query and selection phases of a user search into a discrete session for billing purposes. We recommend using session tokens for all autocomplete sessions. The session begins when the user starts typing a query, and concludes when they select a place. Each session can have multiple queries, followed by one place selection. Once a session has concluded, the token is no longer valid; your app must generate a fresh token for each session.

Field masks

In methods that return place details, you can specify which types of place data to return with each request. This helps to ensure that you only request (and pay for) data that you will use.

To specify which data types to return, pass a GMSPlaceField in your request, as shown in the following example:

Swift

let fields: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.name.rawValue) |
      UInt(GMSPlaceField.placeID.rawValue))!

Objective-C

GMSPlaceField fields = (GMSPlaceFieldName | GMSPlaceFieldPlaceID);

You can use one or more of the following fields:

  • GMSPlaceFieldName
  • GMSPlaceFieldPlaceID
  • GMSPlaceFieldPlusCode
  • GMSPlaceFieldCoordinate
  • GMSPlaceFieldOpeningHours
  • GMSPlaceFieldPhoneNumber
  • GMSPlaceFieldFormattedAddress
  • GMSPlaceFieldRating
  • GMSPlaceFieldPriceLevel
  • GMSPlaceFieldTypes
  • GMSPlaceFieldWebsite
  • GMSPlaceFieldViewport
  • GMSPlaceFieldAddressComponents
  • GMSPlaceFieldPhotos
  • GMSPlaceFieldUserRatingsTotal
  • GMSPlaceFieldAll

New classes and properties

Place Picker is deprecated

The Place Picker is deprecated as of January 29, 2019. This feature will be turned off on July 29, 2019, and will no longer be available after that date. To continue using the Place Picker through the deprecation period:

  • Do NOT migrate to the new SDK yet, as the Place Picker is not supported.
  • Do NOT disable the Places SDK for iOS in your Google Cloud Platform project, as doing so will also disable the Place Picker.

다음에 대한 의견 보내기...