Erste Schritte mit dem Consumer SDK für iOS

Mit dem Consumer SDK können Sie eine einfache in die Backend-Dienste der On-Demand-Lösung „Rides and Deliveries“ eingebunden. Sie können eine Fahrt- und Bestellfortschritts-App erstellen, die eine aktive Fahrt anzeigen kann, auf Fahrtaktualisierungen zu reagieren und Fahrtfehler zu beheben.

Da das Consumer SDK eine modulare Architektur hat, die Teile der API verwenden können, die Sie für Ihre App nutzen möchten, und Integrieren Sie sie in Ihre eigenen APIs, Back-End-Dienste der Flotte. Engine und zusätzliche APIs der Google Maps Platform

Mindestsystemanforderungen

  • Auf dem Mobilgerät muss iOS 14 oder höher installiert sein.
  • Xcode Version 15 oder höher.
  • Projektkonfiguration

    Swift-Paketmanager

    Das Consumer SDK kann über installiert werden. Swift Package Manager Damit du das SDK hinzufügen kannst, alle vorhandenen Consumer SDK-Abhängigkeiten entfernt wurden.

    So fügen Sie das SDK einem neuen oder vorhandenen Projekt hinzu:

    1. Öffne deinen Xcode project oder workspace und klicke auf Datei > Paketabhängigkeiten hinzufügen.
    2. Geben Sie https://github.com/googlemaps/ios-consumer-sdk als URL ein und drücken Sie die Eingabetaste. um das Paket zu laden, und klicke auf „Paket hinzufügen“.
    3. Um eine bestimmte version zu installieren, legen Sie das Feld Abhängigkeitsregel auf eine der folgenden Werte fest: zu den versionsbasierten Optionen. Für neue Projekte empfehlen wir, die neueste Version und mit der Spalte „Exakte Version“ Option. Klicke anschließend auf „Paket hinzufügen“.
    4. Prüfe im Fenster Paketprodukte auswählen, ob GoogleRidesharingConsumer hinzugefügt wird Ihr festgelegtes Ziel für main. Klicke anschließend auf „Paket hinzufügen“.
    5. Um die Installation zu überprüfen, navigiere zum Bereich General deines Ziels. Die installierten Pakete sollten nun unter Frameworks, Bibliotheken und eingebettete Inhalte zu sehen sein. Sie können auch die „Paketabhängigkeiten“ von Projektnavigator um das Paket und seine Version zu überprüfen.

    So aktualisieren Sie package für ein vorhandenes Projekt:

    1. Wenn Sie ein Upgrade von einer früheren Version als 9.0.0 durchführen,müssen Sie die folgenden Abhängigkeiten: GoogleMapsBase, GoogleMapsCore und GoogleMapsM4B nach dem Upgrade. Entfernen Sie nicht die Abhängigkeit für GoogleMaps Weitere Informationen finden Sie in der Versionshinweise zu Version 9.0.0

      Gehen Sie in den Konfigurationseinstellungen des Xcode-Projekts zu Frameworks, Libraries, und eingebettete Inhalte. Verwenden Sie das Minuszeichen(-), um das folgende Framework zu entfernen:

      • GoogleMapsBase (nur für Upgrades von Versionen vor 9.0.0)
      • GoogleMapsCore (nur für Upgrades von Versionen vor 9.0.0)
      • GoogleMapsM4B (nur für Upgrades von Versionen vor 9.0.0)
    2. Gehen Sie in Xcode zu „File > Pakete > Auf neueste Paketversionen aktualisieren“.
    3. Um die Installation zu überprüfen, gehen Sie in der Projektnavigation zum Abschnitt Paketabhängigkeiten. um das Paket und seine Version zu überprüfen.

    So entfernen Sie vorhandene Consumer SDK-Abhängigkeiten, die mit hinzugefügt wurden: CocoaPods, gehen Sie so vor:

    1. Schließen Sie den Xcode-Arbeitsbereich. Öffnen Sie das Terminal und führen Sie den folgenden Befehl aus:
      sudo gem install cocoapods-deintegrate cocoapods-clean 
      pod deintegrate 
      pod cache clean --all
    2. Entfernen Sie Podfile, Podfile.resolved und den Xcode workspace, wenn du sie ausschließlich für CocoaPods verwendest.

    Vorhandenes installiertes Consumer SDK entfernen können Sie diese Schritte manuell ausführen:

    1. Suchen Sie in den Konfigurationseinstellungen Ihres Xcode-Projekts nach Frameworks, Bibliotheken und eingebettete Inhalte. Mit dem Minuszeichen(-) entfernen Sie folgendes Framework:

      • GoogleRidesharingConsumer.xcframework
    2. Entfernen Sie aus dem Verzeichnis der obersten Ebene Ihres Xcode-Projekts den GoogleRidesharingConsumer Bundle.

    CocoaPods

    Um das Consumer SDK mit CocoaPods zu konfigurieren, benötigen Sie Folgendes:

    • CocoaPods-Tool: Öffnen Sie zum Installieren des Tools das Terminal und führen Sie den folgenden Befehl.

      sudo gem install cocoapods
      

    Weitere Informationen im Artikel Erste Schritte mit CocoaPods für weitere Informationen Details.

    1. Podfile für das Consumer SDK erstellen und verwenden um die API und ihre Abhängigkeiten zu installieren. Erstellen Sie zunächst eine Datei mit dem Namen Podfile in Ihrem Projektverzeichnis. In dieser Datei ist definiert, Abhängigkeiten. Bearbeiten Sie dann die Podfile-Datei und fügen Sie Ihre Abhängigkeiten hinzu. Hier ist Ein Beispiel mit den Abhängigkeiten:

        source "https://github.com/CocoaPods/Specs.git"
      
        target 'YOUR_APPLICATION_TARGET_NAME_HERE' do
          pod 'GoogleRidesharingConsumer'
        end
      
    2. Speichern Sie die Podfile-Datei. Öffnen Sie ein Terminal und wechseln Sie zum Verzeichnis mit den Podfile:

      cd <path-to-project>
      
    3. Führen Sie den Befehl „pod install“ aus. Dadurch werden die APIs installiert, die im Podfile und mögliche Abhängigkeiten.

      pod install
      
    4. Schließen Sie Xcode und öffnen Sie dann per Doppelklick die .xcworkspace-Datei Ihres Projekts. um Xcode zu starten. Verwenden Sie die .xcworkspace, um das Projekt später zu öffnen -Datei.

    Manuelle Installation

    Ein XCFramework ist ein Binärpaket, mit dem Sie das Consumer SDK: Sie können dieses Paket auf mehreren einschließlich Maschinen mit dem M1-Chipsatz. In diesem Leitfaden erfahren Sie, wie Sie das XCFramework, das die Consumer SDK zu Ihrem Projekt hinzufügen und Ihr Einstellungen in Xcode ändern.

    Laden Sie das SDK-Binärprogramm und die Ressourcen herunter:

    1. Entpacken Sie die ZIP-Dateien, um auf XCFramework und Ressourcen zuzugreifen.

    2. Starten Sie Xcode und öffnen Sie entweder ein vorhandenes Projekt oder erstellen Sie ein neues Projekt arbeiten. Wenn Sie neu bei iOS sind, erstellen Sie ein neues Projekt und wählen Sie App-Vorlage.

    3. Erstellen Sie eine Frameworks-Gruppe in Ihrer Projektgruppe, falls noch keine vorhanden ist bereits.

    4. Ziehen Sie die Datei GoogleRidesharingConsumer.xcframework in Ihr Projekt unter Frameworks, Libraries, and Embedded Content (Frameworks, Bibliotheken und eingebettete Inhalte), um das Consumer SDK zu installieren. Wählen Sie bei Aufforderung Elemente kopieren (falls erforderlich) aus.

    5. Ziehen Sie die heruntergeladene Datei GoogleRidesharingConsumer.bundle in das Verzeichnis der obersten Ebene Ihres Xcode-Projekts. Wenn Sie dazu aufgefordert werden, wählen Sie Copy items if needed aus.

    6. Wählen Sie im Project Navigator Ihr Projekt und dann Anwendungsziel.

    7. Öffnen Sie den Tab Build Phases (Build-Phasen) und fügen Sie in Link Binary with Libraries (Binärdatei mit Bibliotheken verknüpfen) den Parameter folgenden Frameworks und Bibliotheken, falls diese noch nicht vorhanden sind:

      • 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. Wählen Sie Ihr Projekt anstelle eines bestimmten Ziels aus und öffnen Sie die Schaltfläche Build Einstellungen. Fügen Sie im Abschnitt Other Linker Flags (Weitere Verknüpfungs-Flags) -ObjC für Debug und Release. Sind diese Einstellungen nicht sichtbar, ändern Sie die filtern Sie in der Leiste mit den Build-Einstellungen von Einfach nach Alle.

    Apple Privacy Manifest-Datei prüfen

    Apple verlangt, dass für Apps im App Store Details zum App-Datenschutz angegeben werden. Aktuelle Informationen und weitere Informationen finden Sie auf der Seite zu Datenschutzdetails im Apple App Store.

    Die Apple Privacy Manifest-Datei ist im Ressourcenpaket für das SDK enthalten. Wenn Sie prüfen möchten, ob die Privacy Manifest-Datei enthalten ist, und ihren Inhalt prüfen möchten, erstellen Sie ein Archiv Ihrer App und generieren Sie aus dem Archiv einen Datenschutzbericht.

    Anwendungseinbindung

    Authentifizierungstoken angeben

    Wenn Ihre Nutzeranwendung Updates zu Fahrten von Fleet Engine anfordert, muss gültige Zugriffstokens enthalten. Um diese Anfragen zu autorisieren und zu authentifizieren, ruft das Consumer SDK Ihr Objekt in Übereinstimmung mit dem GMTCAuthorization-Protokoll. Das -Objekt ist für die Bereitstellung des das erforderliche Zugriffstoken.

    Als App-Entwickler entscheiden Sie, wie Tokens generiert werden. Ihre Implementierung sollte Folgendes ermöglichen:

    • Rufen Sie ein Zugriffstoken im JSON-Format von einem HTTPS-Server ab.
    • Parsen Sie das Token und speichern Sie es im Cache.
    • Aktualisieren Sie das Token, wenn es abläuft.

    Einzelheiten zu den vom Fleet Engine-Server erwarteten Tokens finden Sie unter Erstellen eines JSON Web Token (JWT) für Autorisierung.

    Die Anbieter-ID ist mit der Google Cloud-Projekt-ID identisch. Weitere Informationen Siehe Erste Schritte mit Fleet Suchmaschine

    Im folgenden Beispiel wird ein Zugriffstokenanbieter implementiert:

    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
    

    Anwendungsinitialisierung

    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
    

    Einbindung von Kartenansichten

    Kartenansicht initialisieren

    Das folgende Beispiel zeigt, wie GMTCMapView initialisiert wird.

    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
    

    Kartenansichtsereignisse verarbeiten

    Das folgende Beispiel zeigt, wie ein Bevollmächtigter für die Verarbeitung des Kundenstatus implementiert wird Ereignisse.

    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.
    }
    

    Reise teilen

    Neue Fahrt starten, nachdem die Ansicht geladen wurde

    Das folgende Beispiel zeigt, wie Sie direkt nach der geladenen Ansichten. Sie können alle Nutzereingaben wie Abgabe- und Abholorte erfassen. aus einem ViewController und erstellen Sie dann eine neue ViewController, um ihre Reise direkt teilen.

    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];
    }
    

    Aktive Fahrt streichen

    Das folgende Beispiel zeigt, wie die aktuell aktive Fahrt zurückgesetzt wird.

    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];
    }
    

    Auf Updates zu Fahrten warten

    Das folgende Beispiel zeigt, wie der tripModel-Callback registriert wird.

    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];
      ...
    }
    

    Das folgende Beispiel zeigt, wie die Registrierung der tripModel storniert wird Callback des Nutzers an.

    Swift

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

    Objective-C

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

    Das folgende Beispiel zeigt, wie GMTCTripModelSubscriber implementiert wird Protokoll zur Verarbeitung von Callbacks, wenn der Fahrtstatus aktualisiert wird.

    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.
    }
    

    Fehlerbehandlung

    Wenn Sie tripModel abonniert haben und ein Fehler auftritt, können Sie den Callback von tripModel durch Implementieren der delegate-Methode tripModel(_:didFailUpdateTripWithError:) Fleet Engine hat den Fehler generiert die dem Google Cloud-Fehlerstandard entspricht. Für den Detailfehler die Definition der Meldung und alle Fehlercodes auf Google Cloud-Fehler Dokumentation.

    Insbesondere für die Fahrtüberwachung ist eine gültige Authentifizierung erforderlich. Token. 401 UNAUTHENTICATED wird ausgegeben, wenn keine gültige Authentifizierung vorhanden ist wie das Token abgelaufen ist.403 PERMISSION_DENIED wird erhöht, wenn der Der Aufrufer hat keine Berechtigung zum Aufrufen einer bestimmten API (z. B. Nutzer mit Consumer Rolle versucht, updateTrip aufzurufen, oder die Anfrage enthält keine gültige „vehicle_id“/„trip_id“. im JWT-Token.

    Weitere Informationen findest du unter Consumer SDK Error (Fehler mit dem Consumer SDK). Handhabung.

    UI-Anpassung

    Benutzerdefinierte Polylinien-UI-Optionen abrufen und festlegen

    Das folgende Beispiel zeigt, wie benutzerdefinierte UI-Optionen für Polylinien festgelegt werden.

    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];
    }
    

    UI-Optionen für benutzerdefinierte Markierungen abrufen und festlegen

    Das folgende Beispiel zeigt, wie benutzerdefinierte UI-Optionen für Markierungen festgelegt werden.

    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];
    }
    

    Kamerazoom anpassen

    Das Feld Mein Standort Schaltfläche im Maps SDK for iOS zentriert die Kamera auf den Gerätestandort.

    Wenn gerade eine Sitzung geteilt wird, können Sie die Kamera zentrieren, sich auf die Reise und nicht nur auf den Standort des Geräts konzentrieren.

    Das Consumer SDK bietet eine automatische Kamerafunktion, ist standardmäßig aktiviert. Die Kamera zoomt, um die Route zu fokussieren, zum nächsten Wegpunkt.

    AutoCamera

    Wenn Sie das Verhalten der Kamera genauer steuern möchten, können Sie sie deaktivieren oder aktivieren. die automatische Kamerafunktion mithilfe der isAllowCameraAutoUpdate Property.

    Weitere Kameraanpassungen finden Sie unter Maps SDK for iOS Moving the Kamera