Reisen auf iOS-Geräten verfolgen

Plattform auswählen: Android iOS JavaScript

Wenn Sie eine Fahrt verfolgen, wird in Ihrer Verbraucher-App der Standort des entsprechenden Fahrzeugs angezeigt. Dazu muss Ihre App eine Fahrt verfolgen, den Fahrtfortschritt aktualisieren und die Verfolgung beenden, wenn die Fahrt abgeschlossen ist.

In diesem Dokument wird beschrieben, wie dieser Prozess funktioniert.

Fahrt folgen

So können Sie eine Fahrt verfolgen:

  • Erfassen Sie alle Nutzereingaben wie Abgabe- und Abholorte aus einem ViewController.

  • Erstellen Sie eine neue ViewController, um eine Fahrt direkt zu verfolgen.

Im folgenden Beispiel wird gezeigt, wie Sie eine Fahrt sofort nach dem Laden der Ansicht verfolgen können.

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

Fahrt nicht mehr folgen

Sie folgen einer Fahrt nicht mehr, wenn sie abgeschlossen oder abgebrochen wurde. Im folgenden Beispiel wird gezeigt, wie Sie die Freigabe der aktiven Fahrt beenden.

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

Fahrtfortschritt aktualisieren

Während einer Fahrt verwalten Sie den Fahrtfortschritt so:

Wenn eine Fahrt abgeschlossen oder abgebrochen wird, beenden Sie das Abrufen von Updates. Ein Beispiel finden Sie unter Beispiel: Auf Updates warten beenden.

Beispiel für das Starten des Wartens auf Updates

Das folgende Beispiel zeigt, wie der Callback tripModel 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];
  ...
}

Beispiel für das Beenden des Wartens auf Updates

Das folgende Beispiel zeigt, wie die Registrierung des tripModel-Callbacks aufgehoben wird.

Swift

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

Objective-C

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

Beispiel für die Verarbeitung von Fahrtaktualisierungen

Das folgende Beispiel zeigt, wie das GMTCTripModelSubscriber-Protokoll implementiert wird, um Callbacks zu verarbeiten, 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.
}

Fahrtfehler beheben

Wenn Sie tripModel abonniert haben und ein Fehler auftritt, können Sie den Callback von tripModel abrufen, indem Sie die Delegatmethode tripModel(_:didFailUpdateTripWithError:) implementieren. Fehlermeldungen entsprechen dem Google Cloud-Fehlerstandard. Detaillierte Definitionen von Fehlermeldungen und alle Fehlercodes finden Sie in der Dokumentation zu Google Cloud-Fehlern.

Hier sind einige häufige Fehler, die beim Monitoring von Fahrten auftreten können:

HTTP RPC Beschreibung
400 INVALID_ARGUMENT Der Client hat einen ungültigen Fahrtnamen angegeben. Der Name der Fahrt muss das Format providers/{provider_id}/trips/{trip_id} haben. Die provider_id muss die ID des Cloud-Projekts sein, das dem Dienstanbieter gehört.
401 UNAUTHENTICATED Dieser Fehler wird angezeigt, wenn keine gültigen Authentifizierungsdaten vorhanden sind. Beispiel: Das JWT-Token wurde ohne Fahrt-ID signiert oder ist abgelaufen.
403 PERMISSION_DENIED Sie erhalten diesen Fehler, wenn der Client nicht über ausreichende Berechtigungen verfügt (z. B. wenn ein Nutzer mit der Rolle „Consumer“ versucht, „updateTrip“ aufzurufen), wenn das JWT-Token ungültig ist oder wenn die API für das Clientprojekt nicht aktiviert ist. Das JWT-Token fehlt möglicherweise oder das Token ist mit einer Fahrt-ID signiert, die nicht mit der angeforderten Fahrt-ID übereinstimmt.
429 RESOURCE_EXHAUSTED Das Ressourcenkontingent ist null oder die Trafficrate überschreitet das Limit.
503 UNAVAILABLE Dienst nicht verfügbar: In der Regel ist der Server ausgefallen.
504 DEADLINE_EXCEEDED Die Frist der Anfrage wurde überschritten. Dieser Fehler tritt nur auf, wenn der Aufrufer eine Frist festlegt, die kürzer als die Standardfrist der Methode ist (d. h. die angeforderte Frist reicht nicht aus, damit der Server die Anfrage verarbeiten kann), und die Anfrage nicht innerhalb der Frist abgeschlossen wurde.

Consumer SDK-Fehler verarbeiten

Das Consumer SDK sendet Fehler bei der Fahrtaktualisierung über einen Callback-Mechanismus an die Verbraucher-App. Der Callback-Parameter ist ein plattformspezifischer Rückgabetyp (TripUpdateError unter Android und NSError unter iOS).

Statuscodes extrahieren

Die an den Callback übergebenen Fehler sind in der Regel gRPC-Fehler. Sie können auch zusätzliche Informationen in Form eines Statuscodes daraus extrahieren. Eine vollständige Liste der Statuscodes finden Sie unter Statuscodes und ihre Verwendung in gRPC.

Swift

NSError wird in tripModel(_:didFailUpdateTripWithError:) zurückgerufen.

// Called when there is a trip update error.
func tripModel(_ tripModel: GMTCTripModel, didFailUpdateTripWithError error: Error?) {
  // Check to see if the error comes from gRPC.
  if let error = error as NSError?, error.domain == "io.grpc" {
    let gRPCErrorCode = error.code
    ...
  }
}

Objective-C

NSError wird in tripModel:didFailUpdateTripWithError: zurückgerufen.

// Called when there is a trip update error.
- (void)tripModel:(GMTCTripModel *)tripModel didFailUpdateTripWithError:(NSError *)error {
  // Check to see if the error comes from gRPC.
  if ([error.domain isEqualToString:@"io.grpc"]) {
    NSInteger gRPCErrorCode = error.code;
    ...
  }
}

Statuscodes interpretieren

Statuscodes decken zwei Arten von Fehlern ab: Server- und netzwerkbezogene Fehler sowie clientseitige Fehler.

Server- und Netzwerkfehler

Die folgenden Statuscodes beziehen sich entweder auf Netzwerk- oder Serverfehler. Sie müssen nichts unternehmen, um sie zu beheben. Das Consumer SDK behebt sie automatisch.

StatuscodeBeschreibung
ABORTED Der Server hat das Senden der Antwort beendet. Dies wird normalerweise durch ein Serverproblem verursacht.
ABGEBROCHEN Der Server hat die ausgehende Antwort beendet. Dies geschieht normalerweise, wenn
die App in den Hintergrund verschoben wird oder sich der Status in der
Verbraucher-App ändert.
INTERRUPTED
DEADLINE_EXCEEDED Die Antwort des Servers hat zu lange gedauert.
UNAVAILABLE Der Server war nicht verfügbar. Dies wird normalerweise durch ein Netzwerkproblem verursacht.

Clientfehler

Die folgenden Statuscodes beziehen sich auf Clientfehler, die Sie beheben müssen. Das Consumer SDK versucht weiterhin, die Fahrt zu aktualisieren, bis Sie die Freigabe der Fahrt beenden. Es wird jedoch erst wiederhergestellt, wenn Sie Maßnahmen ergreifen.

StatuscodeBeschreibung
INVALID_ARGUMENT Die Nutzer-App hat einen ungültigen Fahrtnamen angegeben. Der Fahrtname muss das Format providers/{provider_id}/trips/{trip_id} haben.
NOT_FOUND Die Fahrt wurde nie erstellt.
PERMISSION_DENIED Die Consumer-App hat nicht genügend Berechtigungen. Dieser Fehler tritt in folgenden Fällen auf:
  • Die Verbraucher-App hat keine Berechtigungen
  • Das Consumer SDK ist für das Projekt in der Google Cloud Console nicht aktiviert.
  • Das JWT-Token fehlt oder ist ungültig.
  • Das JWT-Token ist mit einer Fahrt-ID signiert, die nicht mit der angeforderten Fahrt übereinstimmt.
RESOURCE_EXHAUSTED Das Ressourcenkontingent ist null oder die Trafficrate überschreitet das Geschwindigkeitslimit.
UNAUTHENTICATED Die Authentifizierung der Anfrage ist aufgrund eines ungültigen JWT-Tokens fehlgeschlagen. Dieser Fehler tritt auf, wenn das JWT-Token ohne Fahrt-ID signiert wurde oder wenn das JWT-Token abgelaufen ist.