Premiers pas avec le SDK grand public pour iOS

Vous pouvez utiliser le SDK client pour créer et exécuter une application grand public de base intégrée aux services de backend de la solution Courses et livraisons à la demande. Vous pouvez créer une application de progression du trajet et de la commande qui peut afficher un trajet actif, répondre aux mises à jour de trajet et gérer les erreurs de trajet.

Étant donné que le SDK client possède une architecture modulaire, vous pouvez utiliser les parties de l'API que vous souhaitez utiliser pour votre application et les intégrer à vos propres API, aux services de backend fournis par Fleet Engine et à des API supplémentaires de Google Maps Platform.

Configuration système minimale requise

  • L'appareil mobile doit exécuter iOS 14 ou une version ultérieure.
  • Xcode version 15 ou ultérieure.
  • Configuration du projet

    Gestionnaire de paquets Swift

    Le SDK grand public peut être installé via Swift Package Manager. Pour ajouter le SDK, assurez-vous d'avoir supprimé toutes les dépendances existantes du SDK client.

    Pour ajouter le SDK à un projet nouveau ou existant, procédez comme suit:

    1. Ouvrez votre fichier Xcode project ou workspace, puis accédez à File > Add Package Dependencies (Fichier > Ajouter des dépendances de packages).
    2. Saisissez https://github.com/googlemaps/ios-consumer-sdk en tant qu'URL, appuyez sur Entrée pour récupérer le package, puis cliquez sur "Add Package" (Ajouter un paquet).
    3. Pour installer un version spécifique, définissez le champ Règle de dépendance sur l'une des options basées sur la version. Pour les nouveaux projets, nous vous recommandons de spécifier la dernière version et d'utiliser l'option "Version exacte". Une fois l'opération terminée, cliquez sur "Ajouter un package".
    4. Dans la fenêtre Choose Package Products (Sélectionner des produits de package), vérifiez que GoogleRidesharingConsumer sera ajouté à la cible main désignée. Une fois l'opération terminée, cliquez sur "Ajouter un package".
    5. Pour vérifier votre installation, accédez au volet General de votre cible. Dans Cadres, bibliothèques et contenu intégré, vous devriez voir les packages installés. Vous pouvez également consulter la section "Package Dependencies" (Dépendances de packages) de "Project Navigator" (Navigateur de projets) pour vérifier le package et sa version.

    Pour mettre à jour le package d'un projet existant, procédez comme suit:

    1. Dans Xcode, accédez à Fichier > Packages > Mettre à jour vers les dernières versions du package.
    2. Pour vérifier votre installation, accédez à la section Package Dependencies (Dépendances de packages) de Project Navigator afin de vérifier le package et sa version.

    Pour supprimer les dépendances existantes du SDK client ajoutées à l'aide de CocoaPods, procédez comme suit:

    1. Fermez votre espace de travail Xcode. Ouvrez le terminal et exécutez la commande suivante :
      sudo gem install cocoapods-deintegrate cocoapods-clean 
      pod deintegrate 
      pod cache clean --all
    2. Supprimez Podfile, Podfile.resolved et Xcode workspace si vous ne les utilisez que pour CocoaPods.

    Pour supprimer le SDK client existant installé manuellement, procédez comme suit:

    1. Dans les paramètres de configuration de votre projet Xcode, recherchez Frameworks, bibliothèques et contenu intégré. Utilisez le signe moins(-) pour supprimer le framework suivant:

      • GoogleRidesharingConsumer.xcframework
    2. Dans le répertoire racine de votre projet Xcode, supprimez le bundle GoogleRidesharingConsumer.

    CocoaPods

    Pour configurer le SDK client à l'aide de CocoaPods, vous avez besoin des éléments suivants:

    • L'outil CocoaPods: pour installer cet outil, ouvrez le terminal et exécutez la commande suivante.

      sudo gem install cocoapods
      

    Pour en savoir plus, consultez le guide de démarrage de CocoaPods.

    1. Créer un fichier Podfile pour le SDK client et l'utiliser pour installer l'API et ses dépendances Commencez par créer un fichier nommé Podfile dans le répertoire de votre projet. Ce fichier définit les dépendances de votre projet. Modifiez ensuite le fichier Podfile et ajoutez vos dépendances. Voici un exemple incluant les dépendances:

        source "https://github.com/CocoaPods/Specs.git"
      
        target 'YOUR_APPLICATION_TARGET_NAME_HERE' do
          pod 'GoogleRidesharingConsumer'
        end
      
    2. Enregistrez le fichier Podfile. Ouvrez un terminal et accédez au répertoire contenant le fichier Podfile:

      cd <path-to-project>
      
    3. Exécutez la commande "pod install". Cette action installera les API spécifiées dans le Podfile, ainsi que toutes leurs dépendances.

      pod install
      
    4. Fermez Xcode, puis ouvrez (double-cliquez) le fichier .xcworkspace de votre projet pour lancer Xcode. Pour ouvrir le projet ultérieurement, utilisez le fichier .xcworkspace.

    Installation manuelle

    Un XCFramework est un package binaire que vous utilisez pour installer le SDK client. Vous pouvez utiliser ce package sur plusieurs plates-formes, y compris sur les machines utilisant le chipset M1. Ce guide explique comment ajouter manuellement le XCFramework contenant le SDK client à votre projet et configurer les paramètres de compilation dans Xcode.

    Téléchargez le binaire et les ressources du SDK:

    1. Décompressez les fichiers compressés pour accéder à XCFramework et aux ressources.

    2. Démarrez Xcode, puis ouvrez un projet existant ou créez-en un. Si vous débutez avec iOS, créez un projet et sélectionnez le modèle d'application iOS.

    3. Créez un groupe Frameworks dans votre groupe de projets s'il n'en existe pas déjà un.

    4. Pour installer le SDK client, faites glisser le fichier GoogleRidesharingConsumer.xcframework dans votre projet sous Frameworks, bibliothèques et contenu intégré. Lorsque vous y êtes invité, sélectionnez "Copier des éléments" si nécessaire.

    5. Faites glisser le fichier GoogleRidesharingConsumer.bundle téléchargé dans le répertoire de premier niveau de votre projet Xcode. Lorsque vous y êtes invité, sélectionnez Copy items if needed.

    6. Sélectionnez votre projet dans Project Navigator, puis choisissez la cible de votre application.

    7. Ouvrez l'onglet "Build Phases" (Phases de compilation), puis, dans le champ "Link Binary with Libraries" (Associer le binaire avec des bibliothèques), ajoutez les frameworks et bibliothèques suivants si ils ne sont pas déjà présents:

      • Accelerate.framework
      • CoreData.framework
      • CoreGraphics.framework
      • CoreImage.framework
      • CoreLocation.framework
      • CoreTelephony.framework
      • CoreText.framework
      • GLKit.framework
      • ImageIO.framework
      • libc++.tbd
      • libz.tbd
      • Metal.framework
      • OpenGLES.framework
      • QuartzCore.framework
      • SystemConfiguration.framework
      • UIKit.framework
    8. Choisissez votre projet plutôt qu'une cible spécifique, puis ouvrez l'onglet Build Settings (Paramètres de compilation). Dans la section Autres options Linker, ajoutez -ObjC pour le débogage et la publication. Si ces paramètres ne sont pas visibles, remplacez le filtre Basic (De base) par All (Tous) dans la barre des paramètres de compilation.

    Ajouter un fichier manifeste de confidentialité Apple

    1. Téléchargez le package du fichier manifeste de confidentialité pour le SDK grand public pour iOS: GoogleRidesharingConsumerPrivacy.
    2. Extrayez le fichier pour accéder à GoogleRidesharingConsumerPrivacy.bundle.
    3. Ajoutez GoogleRidesharingConsumerPrivacy.bundle au navigateur de projet Xcode à l'aide de l'une de ces méthodes. Assurez-vous que la case "Ajouter aux cibles" est cochée pour la cible de votre application. Une fois ajouté, le fichier PrivacyInfo s'affiche dans le navigateur de projets, et vous pouvez inspecter ses valeurs.
    4. Capture d&#39;écran des informations sur la confidentialité dans Xcode
    5. Vérifiez que le fichier manifeste de confidentialité a été ajouté en créant une archive de votre application et en générant un rapport de confidentialité à partir de cette archive.

    Intégration d'applications

    Fournir un jeton d'authentification

    Lorsque votre application grand public demande des mises à jour de trajets à Fleet Engine, les requêtes doivent inclure des jetons d'accès valides. Pour autoriser et authentifier ces requêtes, le SDK client appelle votre objet conformément au protocole GMTCAuthorization. L'objet est chargé de fournir le jeton d'accès requis.

    En tant que développeur de l'application, vous choisissez la façon dont les jetons sont générés. Votre implémentation doit permettre d'effectuer les opérations suivantes:

    • Récupérez un jeton d'accès, éventuellement au format JSON, à partir d'un serveur HTTPS.
    • Analyser et mettre en cache le jeton.
    • Actualisez le jeton lorsqu'il expire.

    Pour en savoir plus sur les jetons attendus par le serveur Fleet Engine, consultez la page Créer un jeton Web JSON (JWT) pour l'autorisation.

    L'ID du fournisseur est identique à l'ID du projet Google Cloud. Pour en savoir plus, consultez la page Premiers pas avec Fleet Engine.

    L'exemple suivant implémente un fournisseur de jetons d'accès:

    Swift

    /*
    
        *   SampleAccessTokenProvider.swift
     */
    import GoogleRidesharingConsumer
    
    private let providerURL = "INSERT_YOUR_TOKEN_PROVIDER_URL"
    
    class SampleAccessTokenProvider: NSObject, GMTCAuthorization {
      private struct AuthToken {
        // The cached trip token.
        let token: String
        // Keep track of when the token expires for caching.
        let expiration: TimeInterval
        // Keep track of the trip ID the cached token is for.
        let tripID: String
      }
    
      enum AccessTokenError: Error {
        case missingAuthorizationContext
        case missingData
      }
    
      private var authToken: AuthToken?
    
      func fetchToken(
        with authorizationContext: GMTCAuthorizationContext?,
        completion: @escaping GMTCAuthTokenFetchCompletionHandler
      ) {
        // Get the trip ID from the authorizationContext. This is set by the Consumer SDK.
        guard let authorizationContext = authorizationContext else {
          completion(nil, AccessTokenError.missingAuthorizationContext)
          return
        }
        let tripID = authorizationContext.tripID
    
        // If appropriate, use the cached token.
        if let authToken = authToken,
          authToken.expiration > Date.now.timeIntervalSince1970 && authToken.tripID == tripID
        {
          completion(authToken.token, nil)
          return
        }
    
        // Otherwise, try to fetch a new token from your server.
        let request = URLRequest(url: URL(string: providerURL))
        let task = URLSession.shared.dataTask(with: request) { [weak self] data, _, error in
          guard let strongSelf = self else { return }
          guard error == nil else {
            completion(nil, error)
            return
          }
    
          // Replace the following key values with the appropriate keys based on your
          // server's expected response.
          let tripTokenKey = "TRIP_TOKEN_KEY"
          let tokenExpirationKey = "TOKEN_EXPIRATION"
          guard let data = data,
            let fetchData = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
            let token = fetchData[tripTokenKey] as? String,
            let expiration = fetchData[tokenExpirationKey] as? Double
          else {
            completion(nil, AccessTokenError.missingData)
            return
          }
    
          strongSelf.authToken = AuthToken(token: token, expiration: expiration, tripID: tripID)
          completion(token, nil)
        }
        task.resume()
      }
    }
    

    Objective-C

    /*
    
        *   SampleAccessTokenProvider.h
     */
    #import <Foundation/Foundation.h>
    #import <GoogleRidesharingConsumer/GoogleRidesharingConsumer.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface SampleAccessTokenProvider : NSObject <GMTCAuthorization>
    
    @end
    
    NS_ASSUME_NONNULL_END
    
    /*
    
        *   SampleAccessTokenProvider.m
     */
    #import "SampleAccessTokenProvider.h"
    #import "GoogleRidesharingConsumer/GoogleRidesharingConsumer.h"
    
    static NSString *const PROVIDER_URL = @"INSERT_YOUR_TOKEN_PROVIDER_URL";
    
    // SampleAccessTokenProvider.m
    @implementation SampleAccessTokenProvider {
      // The cached token with claims to the current trip.
      NSString *_cachedTripToken;
      // Keep track of the Trip ID the cached token is for.
      NSString *_lastKnownTripID;
      // Keep track of when tokens expire for caching.
      NSTimeInterval _tokenExpiration;
    }
    
    -   (void)fetchTokenWithContext:(nullable GMTCAuthorizationContext *)authorizationContext
                       completion:(nonnull GMTCAuthTokenFetchCompletionHandler)completion {
      // Get the trip ID from the authorizationContext. This is set by the Consumer SDK.
      NSString *tripID = authorizationContext.tripID;
    
      // Clear cached trip token if trip ID has changed.
      if (![_lastKnownTripID isEqual:tripID]) {
        _tokenExpiration = 0.0;
        _cachedTripToken = nil;
      }
      _lastKnownTripID = tripID;
    
      // Clear cached tripToken if it has expired.
      if ([[NSDate date] timeIntervalSince1970] > _tokenExpiration) {
        _cachedTripToken = nil;
      }
    
      // If appropriate, use the cached token.
      if (_cachedTripToken) {
        completion(_cachedTripToken, nil);
        return;
      }
      // Otherwise, try to fetch a new token from your server.
      NSURL *requestURL = [NSURL URLWithString:PROVIDER_URL];
      NSMutableURLRequest *request =
          [[NSMutableURLRequest alloc] initWithURL:requestURL];
      request.HTTPMethod = @"GET";
    
      // Replace the following key values with the appropriate keys based on your
      // server's expected response.
      NSString *tripTokenKey = @"TRIP_TOKEN_KEY";
      NSString *tokenExpirationKey = @"TOKEN_EXPIRATION";
    
      __weak typeof(self) weakSelf = self;
      void (^handler)(NSData *_Nullable data, NSURLResponse *_Nullable response,
                      NSError *_Nullable error) =
          ^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError *_Nullable error) {
            typeof(self) strongSelf = weakSelf;
            if (error) {
              completion(nil, error);
              return;
            }
    
            NSError *JSONError;
            NSMutableDictionary *JSONResponse =
                [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&JSONError];
    
            if (JSONError) {
              completion(nil, JSONError);
              return;
            } else {
              // Sample code only. No validation logic.
              id expirationData = JSONResponse[tokenExpirationKey];
              if ([expirationData isKindOfClass:[NSNumber class]]) {
                NSTimeInterval expirationTime = ((NSNumber *)expirationData).doubleValue;
                strongSelf->_tokenExpiration = [[NSDate date] timeIntervalSince1970] + expirationTime;
              }
              strongSelf->_cachedTripToken = JSONResponse[tripTokenKey];
              completion(JSONResponse[tripTokenKey], nil);
            }
          };
      NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
      NSURLSession *mainQueueURLSession =
          [NSURLSession sessionWithConfiguration:config delegate:nil
                                   delegateQueue:[NSOperationQueue mainQueue]];
      NSURLSessionDataTask *task = [mainQueueURLSession dataTaskWithRequest:request completionHandler:handler];
      [task resume];
    }
    
    @end
    

    Initialisation de l'application

    Swift

    /*
    
        *   AppDelegate.swift
     */
    import GoogleRidesharingConsumer
    import GoogleMaps
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
      func application(_ application: UIApplication,
          didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Register your API key for GMSServices.
        GMSServices.provideAPIKey(yourMapsAPIKey)
    
        // Set the instance of the SampleAccessTokenProvider.
        GMTCServices.setAccessTokenProvider(SampleAccessTokenProvider(), providerID: yourProviderID)
    
        // Other initialization code ...
        return true
      }
    }
    

    Objective-C

    /*
    
        *   AppDelegate.m
     */
    #import <GoogleMaps/GoogleMaps.h>
    #import <GoogleRidesharingConsumer/GoogleRidesharingConsumer.h>
    
    @implementation AppDelegate
    
    -   (BOOL)application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
      //Register your API key for GMSServices.
      [GMSServices provideAPIKey:yourMapsAPIKey];
    
      //Set the instance of the AccessTokenFactory.
      [GMTCServices setAccessTokenProvider:[[SampleAccessTokenProvider alloc] init]
                                providerID:yourProviderID];
    
      // Other initialization code ...
      return YES;
    }
    
    @end
    

    Intégration de la vue plan

    Initialiser la vue plan

    L'exemple suivant montre comment initialiser GMTCMapView.

    Swift

    /*
    
        *   MapViewController.swift
     */
    class ViewController: UIViewController, GMTCMapViewDelegate {
      private var rideSharingMap: GMTCMapView?
    
      override func viewDidLoad() {
        super.viewDidLoad()
    
        self.rideSharingMap = GMTCMapView(frame: UIScreen.main.bounds)
        self.rideSharingMap.delegate = self
        self.rideSharingMap?.settings.myLocationButton = true
        self.view.addSubview(self.rideSharingMap!)
        ...
      }
    

    Objective-C

    /*
    
        *   MapViewController.h
     */
    @interface MapViewController : UIViewController<GMTCMapViewDelegate>
    ...
    @end
    
    /*
    
        *   MapViewController.m
     */
    @implementation MapViewController
    
    -   (void)viewDidLoad {
      [super viewDidLoad];
      ...
      self.mapView = [[GMTCMapView alloc] initWithFrame:CGRectZero];
      self.mapView.settings.myLocationButton = YES;
      self.mapView.delegate = self;
      ...
    }
    
    ...
    
    @end
    

    Gérer les événements de vue de carte

    L'exemple suivant montre comment implémenter un délégué pour gérer les événements d'état client.

    Swift

    func mapViewDidInitialize(_ mapview: GMTCMapView) {
      // Handle the update to the state of the map view to browsing.
    }
    
    func mapView(_ mapView: GMSMapView, didTapConsumerMarker mapMarker: GMSMarker, markerType: GMTCMapViewMarkerType) -> Bool {
      // Handle the mapView marker was tapped.
    }
    

    Objective-C

    /*
    
        *   MapViewController.m
     */
    #pragma mark - GMTCMapViewDelegate implementation
    
    // Handle state update of map view.
    
    -   (void)mapViewDidInitializeCustomerState:(GMTCMapView *)mapview {
      // Handle the update to the state of the map view to browsing.
    }
    
    -   (void)mapView:(GMSMapView *)mapView
        didTapConsumerMarker:(nonnull GMSMarker *)mapMarker
                  markerType:(GMTCMapViewMarkerType)markerType {
      // Handle the mapView marker was tapped.
    }
    

    Partage de parcours

    Commencer un nouveau trajet lorsque la vue a été chargée

    L'exemple suivant montre comment démarrer un partage de parcours immédiatement après le chargement de la vue. Vous pouvez rassembler toutes les entrées utilisateur, telles que les lieux de dépôt et de prise en charge à partir d'un ViewController, puis créer un ViewController pour démarrer directement le partage du parcours.

    Swift

    /*
    
        *   MapViewController.swift
     */
    override func viewDidLoad() {
      super.viewDidLoad()
      ...
      self.mapView = GMTCMapView(frame: UIScreen.main.bounds)
      self.mapView.delegate = self
      self.view.addSubview(self.mapView)
    }
    
    func mapViewDidInitializeCustomerState(_: GMTCMapView) {
      self.mapView.pickupLocation = self.selectedPickupLocation
      self.mapView.dropoffLocation = self.selectedDropoffLocation
    
      self.startConsumerMatchWithLocations(
        pickupLocation: self.mapView.pickupLocation!,
        dropoffLocation: self.mapView.dropoffLocation!
      ) { [weak self] (tripName, error) in
        guard let strongSelf = self else { return }
        if error != nil {
          // print error message.
          return
        }
        let tripService = GMTCServices.shared().tripService
        // Create a tripModel instance for listening the update of the trip
        // specified by this trip name.
        let tripModel = tripService.tripModel(forTripName: tripName)
        // Create a journeySharingSession instance based on the tripModel
        let journeySharingSession = GMTCJourneySharingSession(tripModel: tripModel)
        // Add the journeySharingSession instance on the mapView for UI updating.
        strongSelf.mapView.show(journeySharingSession)
        // Register for the trip update events.
        tripModel.register(strongSelf)
    
        strongSelf.currentTripModel = tripModel
        strongSelf.currentJourneySharingSession = journeySharingSession
        strongSelf.hideLoadingView()
      }
    
      self.showLoadingView()
    }
    

    Objective-C

    /*
    
        *   MapViewController.m
     */
    -   (void)viewDidLoad {
      [super viewDidLoad];
      ...
      self.mapView = [[GMTCMapView alloc] initWithFrame:CGRectZero];
      self.mapView.delegate = self;
      [self.view addSubview:self.mapView];
    }
    
    // Handle the callback when the GMTCMapView did initialized.
    
    -   (void)mapViewDidInitializeCustomerState:(GMTCMapView *)mapview {
      self.mapView.pickupLocation = self.selectedPickupLocation;
      self.mapView.dropoffLocation = self.selectedDropoffLocation;
    
      __weak __typeof(self) weakSelf = self;
      [self startTripBookingWithPickupLocation:self.selectedPickupLocation
                               dropoffLocation:self.selectedDropoffLocation
                                    completion:^(NSString *tripName, NSError *error) {
                                      __typeof(self) strongSelf = weakSelf;
                                      GMTCTripService *tripService = [GMTCServices sharedServices].tripService;
                                      // Create a tripModel instance for listening to updates to the trip specified by this trip name.
                                      GMTCTripModel *tripModel = [tripService tripModelForTripName:tripName];
                                      // Create a journeySharingSession instance based on the tripModel.
                                      GMTCJourneySharingSession *journeySharingSession =
                                        [[GMTCJourneySharingSession alloc] initWithTripModel:tripModel];
                                      // Add the journeySharingSession instance on the mapView for updating the UI.
                                      [strongSelf.mapView showMapViewSession:journeySharingSession];
                                      // Register for trip update events.
                                      [tripModel registerSubscriber:self];
    
                                      strongSelf.currentTripModel = tripModel;
                                      strongSelf.currentJourneySharingSession = journeySharingSession;
                                      [strongSelf hideLoadingView];
                                    }];
        [self showLoadingView];
    }
    

    Annuler le trajet en cours

    L'exemple suivant montre comment réinitialiser le trajet actif en cours.

    Swift

    /*
    
        *   MapViewController.swift
     */
    func cancelCurrentActiveTrip() {
      // Stop the tripModel
      self.currentTripModel.unregisterSubscriber(self)
    
      // Remove the journey sharing session from the mapView's UI stack.
      self.mapView.hide(journeySharingSession)
    }
    

    Objective-C

    /*
    
        *   MapViewController.m
     */
    -   (void)cancelCurrentActiveTrip {
      // Stop the tripModel
      [self.currentTripModel unregisterSubscriber:self];
    
      // Remove the journey sharing session from the mapView's UI stack.
      [self.mapView hideMapViewSession:journeySharingSession];
    }
    

    Écouter les informations sur le trajet

    L'exemple suivant montre comment enregistrer le rappel tripModel.

    Swift

    /*
    
        *   MapViewController.swift
     */
    override func viewDidLoad() {
      super.viewDidLoad()
      // Register for trip update events.
      self.currentTripModel.register(self)
    }
    

    Objective-C

    /*
    
        *   MapViewController.m
     */
    -   (void)viewDidLoad {
      [super viewDidLoad];
      // Register for trip update events.
      [self.currentTripModel registerSubscriber:self];
      ...
    }
    

    L'exemple suivant montre comment annuler l'enregistrement du rappel tripModel.

    Swift

    /*
    
        *   MapViewController.swift
     */
    deinit {
      self.currentTripModel.unregisterSubscriber(self)
    }
    

    Objective-C

    /*
    
        *   MapViewController.m
     */
    -   (void)dealloc {
      [self.currentTripModel unregisterSubscriber:self];
      ...
    }
    

    L'exemple suivant montre comment implémenter le protocole GMTCTripModelSubscriber pour gérer les rappels lorsque l'état du trajet est mis à jour.

    Swift

    /*
    
        *   MapViewController.swift
     */
    func tripModel(_: GMTCTripModel, didUpdate trip: GMTSTrip?, updatedPropertyFields: GMTSTripPropertyFields) {
      // Update the UI with the new `trip` data.
      self.updateUI(with: trip)
    }
    
    func tripModel(_: GMTCTripModel, didUpdate tripStatus: GMTSTripStatus) {
      // Handle trip status did change.
    }
    
    func tripModel(_: GMTCTripModel, didUpdateActiveRouteRemainingDistance activeRouteRemainingDistance: Int32) {
      // Handle remaining distance of active route did update.
    }
    
    func tripModel(_: GMTCTripModel, didUpdateActiveRoute activeRoute: [GMTSLatLng]?) {
      // Handle trip active route did update.
    }
    
    func tripModel(_: GMTCTripModel, didUpdate vehicleLocation: GMTSVehicleLocation?) {
      // Handle vehicle location did update.
    }
    
    func tripModel(_: GMTCTripModel, didUpdatePickupLocation pickupLocation: GMTSTerminalLocation?) {
      // Handle pickup location did update.
    }
    
    func tripModel(_: GMTCTripModel, didUpdateDropoffLocation dropoffLocation: GMTSTerminalLocation?) {
      // Handle drop off location did update.
    }
    
    func tripModel(_: GMTCTripModel, didUpdatePickupETA pickupETA: TimeInterval) {
      // Handle the pickup ETA did update.
    }
    
    func tripModel(_: GMTCTripModel, didUpdateDropoffETA dropoffETA: TimeInterval) {
      // Handle the drop off ETA did update.
    }
    
    func tripModel(_: GMTCTripModel, didUpdateRemaining remainingWaypoints: [GMTSTripWaypoint]?) {
      // Handle updates to the pickup, dropoff or intermediate destinations of the trip.
    }
    
    func tripModel(_: GMTCTripModel, didFailUpdateTripWithError error: Error?) {
      // Handle the error.
    }
    
    func tripModel(_: GMTCTripModel, didUpdateIntermediateDestinations intermediateDestinations: [GMTSTerminalLocation]?) {
      // Handle the intermediate destinations being updated.
    }
    
    func tripModel(_: GMTCTripModel, didUpdateActiveRouteTraffic activeRouteTraffic: GMTSTrafficData?) {
      // Handle trip active route traffic being updated.
    }
    

    Objective-C

    /*
    
        *   MapViewController.m
     */
    #pragma mark - GMTCTripModelSubscriber implementation
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
                didUpdateTrip:(nullable GMTSTrip *)trip
        updatedPropertyFields:(enum GMTSTripPropertyFields)updatedPropertyFields {
      // Update the UI with the new `trip` data.
      [self updateUIWithTrip:trip];
      ...
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel didUpdateTripStatus:(enum GMTSTripStatus)tripStatus {
      // Handle trip status did change.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
        didUpdateActiveRouteRemainingDistance:(int32_t)activeRouteRemainingDistance {
       // Handle remaining distance of active route did update.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
        didUpdateActiveRoute:(nullable NSArray<GMTSLatLng *> *)activeRoute {
      // Handle trip active route did update.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
        didUpdateVehicleLocation:(nullable GMTSVehicleLocation *)vehicleLocation {
      // Handle vehicle location did update.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
        didUpdatePickupLocation:(nullable GMTSTerminalLocation *)pickupLocation {
      // Handle pickup location did update.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
        didUpdateDropoffLocation:(nullable GMTSTerminalLocation *)dropoffLocation {
      // Handle drop off location did update.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel didUpdatePickupETA:(NSTimeInterval)pickupETA {
      // Handle the pickup ETA did update.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
        didUpdateRemainingWaypoints:(nullable NSArray<GMTSTripWaypoint *> *)remainingWaypoints {
      // Handle updates to the pickup, dropoff or intermediate destinations of the trip.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel didUpdateDropoffETA:(NSTimeInterval)dropoffETA {
      // Handle the drop off ETA did update.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel didFailUpdateTripWithError:(nullable NSError *)error {
      // Handle the error.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
        didUpdateIntermediateDestinations:
            (nullable NSArray<GMTSTerminalLocation *> *)intermediateDestinations {
      // Handle the intermediate destinations being updated.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
        didUpdateActiveRouteTraffic:(nullable GMTSTrafficData *)activeRouteTraffic {
      // Handle trip active route traffic being updated.
    }
    

    Gestion des exceptions

    Si vous avez abonné le tripModel et qu'une erreur se produit, vous pouvez obtenir le rappel de tripModel en implémentant la méthode déléguée tripModel(_:didFailUpdateTripWithError:). Fleet Engine a généré le message d'erreur qui respecte la norme Google Cloud Error. Pour obtenir la définition détaillée du message d'erreur et tous les codes d'erreur, reportez-vous à la documentation sur les erreurs Google Cloud.

    Plus précisément, pour la surveillance des trajets, vous devez fournir un jeton d'authentification valide. 401 UNAUTHENTICATED est généré s'il n'y a pas d'identifiants d'authentification valides (par exemple, si le jeton a expiré). 403 PERMISSION_DENIED est généré si l'appelant n'est pas autorisé à appeler une API spécifique (par exemple, un utilisateur ayant le rôle de consommateur tente d'appeler updateTrip) ou si la requête n'a pas d'identifiant de véhicule ou de trajet (trip_id) valide dans le jeton JWT.

    Pour en savoir plus, consultez la page Gestion des erreurs du SDK client.

    Personnalisation de l'interface utilisateur

    Obtenir et définir les options d'interface utilisateur des polylignes personnalisées

    L'exemple suivant montre comment définir des options d'interface utilisateur personnalisées pour les polylignes.

    Swift

    /** MapViewController.swift */
    
    func updatePolylineUIOptions() {
      // The polyline type that you would like to set custom UI options for.
      let customizablePolylineType = GMTCPolylineType.activeRoute
    
      let polylineStyleOptions = GMTCMutablePolylineStyleOptions()
      polylineStyleOptions.strokeWidth = 8.0
      polylineStyleOptions.strokeColor = .blue
      polylineStyleOptions.isVisible = true
      polylineStyleOptions.zIndex = 1000
      polylineStyleOptions.isGeodesic = true
      let coordinator = self.mapView.consumerMapStyleCoordinator
      coordinator.setPolylineStyleOptions(polylineStyleOptions, polylineType:customizablePolylineType)
    }
    

    Objective-C

    /** MapViewController.m */
    
    -   (void)updatePolylineUIOptions {
      // The polyline type that you would like to set custom UI options for.
      GMTCPolylineType customizablePolylineType = GMTCPolylineTypeActiveRoute;
    
      GMTCMutablePolylineStyleOptions *polylineStyleOptions =
          [[GMTCMutablePolylineStyleOptions alloc] init];
      polylineStyleOptions.strokeWidth = 8.0;
      polylineStyleOptions.strokeColor = [UIColor blueColor];
      polylineStyleOptions.isVisible = YES;
      polylineStyleOptions.zIndex = 1000;
      polylineStyleOptions.isGeodesic = YES;
      [[_mapView consumerMapStyleCoordinator] setPolylineStyleOptions:polylineStyleOptions
                                                    polylineType:customizablePolylineType];
    }
    

    Obtenir et définir les options d'interface utilisateur des repères personnalisés

    L'exemple suivant montre comment définir des options d'interface utilisateur personnalisées pour les repères.

    Swift

    /** MapViewController.swift */
    
    func updateMarkerUIOptions() {
      let customizableMarkerType = GMTCCustomizableMarkerType.tripVehicle
      let markerStyleOptions = GMTCMutableMarkerStyleOptions()
      markerStyleOptions.groundAnchor = groundAnchor
      markerStyleOptions.isVisible = true
      markerStyleOptions.icon = icon
      markerStyleOptions.zIndex = 100
      markerStyleOptions.isFlat = false
      let coordinator = self.mapView.consumerMapStyleCoordinator
      coordinator.setMarkerStyleOptions(markerStyleOptions, markerType: customizableMarkerType)
    }
    

    Objective-C

    /** MapViewController.m */
    
    -   (void)updateMarkerUIOptions {
      // The marker type that you would like to set custom UI options for.
      GMTCCustomizableMarkerType customizableMarkerType = GMTCCustomizableMarkerTypeTripVehicle;
    
      GMTCMutableMarkerStyleOptions *markerStyleOptions =
          [[GMTCMutableMarkerStyleOptions alloc] init];
      markerStyleOptions.groundAnchor = groundAnchor;
      markerStyleOptions.isVisible = YES;
      markerStyleOptions.icon = icon;
      markerStyleOptions.zIndex = 100;
      markerStyleOptions.isFlat = NO;
    
      [[_mapView consumerMapStyleCoordinator] setMarkerStyleOptions:markerStyleOptions markerType:customizableMarkerType];
    }
    

    Ajuster le zoom de la caméra

    Dans le SDK Maps pour iOS, le bouton "Ma position" centre la caméra sur la position de l'appareil.

    Si une session de partage de trajet est active, vous pouvez centrer la caméra pour vous concentrer sur le trajet plutôt que sur la position de l'appareil uniquement.

    Le SDK grand public fournit une fonctionnalité d'appareil photo automatique activée par défaut. La caméra effectue un zoom pour se concentrer sur l'itinéraire à partager et le prochain point de cheminement du trajet.

    AutoCamera

    Si vous avez besoin de mieux contrôler le comportement de la caméra, vous pouvez activer ou désactiver la fonctionnalité de caméra automatique à l'aide de la propriété isAllowCameraAutoUpdate.

    Pour découvrir plus de personnalisations de la caméra, consultez Déplacer la caméra dans le SDK Maps pour iOS.