Obserwowanie podróży na urządzeniu z iOS

Wybierz platformę: Android iOS JavaScript

Gdy podążasz za podróżą, aplikacja dla konsumentów wyświetla lokalizację odpowiednim pojazdem. Żeby to zrobić, aplikacja musi się uruchomić śledzić podróż, aktualizować jej postępy i zatrzymywać śledzenie podróży, gdy .

Z tego dokumentu dowiesz się, jak to działa.

Zacznij obserwować podróż

Aby rozpocząć śledzenie podróży z użyciem funkcji udostępniania podróży:

  • Zbierz wszystkie dane użytkownika, takie jak miejsca zwrotu i odbioru z: ViewController.

  • Utwórz nowy projekt ViewController, aby bezpośrednio rozpocząć udostępnianie materiałów.

Ten przykład pokazuje, jak rozpocząć udostępnianie podróży bezpośrednio po widoku.

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

Przestań obserwować podróż

Przestajesz obserwować podróż, która została zakończona lub anulowana. Poniżej pokazuje, jak zatrzymać udostępnianie aktywnej podróży.

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

Zaktualizuj postęp podróży

Podczas podróży możesz zarządzać jej postępami w ten sposób:

Gdy podróż zakończy się lub zostanie anulowana, przestań nasłuchiwać powiadomień. Na przykład zobacz Przykład: Przestań nasłuchiwać aktualizacji.

Przykład funkcji Zacznij nasłuchiwać aktualizacji

Przykład poniżej pokazuje, jak zarejestrować wywołanie zwrotne 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];
  ...
}

Przykład: wyłącz nasłuchiwanie aktualizacji

Ten przykład pokazuje, jak anulować rejestrację domeny tripModel oddzwanianie.

Swift

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

Objective-C

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

Przykład informacji o podróży

Poniższy przykład pokazuje, jak wdrożyć GMTCTripModelSubscriber protokół do obsługi wywołań zwrotnych po aktualizacji stanu podróży.

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

Obsługa błędów związanych z podróżą

Jeśli subskrybujesz: tripModel i wystąpi błąd, możesz poprosić o oddzwonienie tripModel przez wdrożenie metody przekazywania dostępu tripModel(_:didFailUpdateTripWithError:) Błąd są zgodne ze standardem błędów Google Cloud. Szczegółowe informacje o błędzie definicje komunikatów i wszystkie kody błędów znajdziesz tutaj dokumentacji błędów Google Cloud (w języku angielskim).

Oto kilka częstych błędów, które mogą wystąpić podczas monitorowania podróży:

HTTP RPC Opis
400 NIEPRAWIDŁOWY_ARG Klient podał nieprawidłową nazwę podróży. Nazwa podróży musi być zgodna z format: providers/{provider_id}/trips/{trip_id}. provider_id musi być identyfikatorem projektu Cloud należącego do z dostawcą usług.
401 BEZ UWIERZYTELNIANIA Ten błąd występuje, jeśli nie istnieją prawidłowe dane uwierzytelniające. Jeśli na przykład token JWT jest podpisany bez identyfikatora podróży lub tokena JWT wygasła.
403 PERMISSION_DENIED Ten błąd pojawia się, jeśli klient nie ma wystarczających uprawnień (na przykład użytkownik z rolą konsumenta próbuje wywołać funkcję updateTrip), jeśli token JWT jest nieprawidłowy lub interfejs API nie jest włączony w projekcie klienta. Być może brakuje tokena JWT lub jest on podpisany za pomocą identyfikatora podróży, nie pasuje do żądanego identyfikatora podróży.
429 RESOURCE_EXHAUSTED Limit zasobów wynosi zero lub tempo ruchu przekracza limit.
503 PRODUKT NIEDOSTĘPNY Usługa niedostępna Zwykle serwer nie działa.
504 DEADLINE_EXCEEDED Przekroczono termin prośby. Ten błąd występuje tylko wtedy, gdy wywołujący termin, który jest krótszy niż domyślny termin metody (czyli żądany termin nie wystarcza do przetworzenia żądania przez serwer) oraz prośba nie została zrealizowana w terminie.

Obsługa błędów pakietów SDK dla konsumentów

Pakiet SDK Consumer SDK wysyła do aplikacji konsumenta błędy aktualizacji podróży za pomocą wywołania zwrotnego . Parametr wywołania zwrotnego jest typem zwrotu specyficznym dla platformy ( TripUpdateError na Androidzie oraz NSError w systemie iOS).

Wyodrębnianie kodów stanu

Błędy przekazywane do wywołania zwrotnego są zwykle błędami gRPC. Możesz również wyodrębnienia z nich dodatkowych informacji w postaci kodu stanu. W przypadku atrybutu pełna lista kodów stanu, patrz Kody stanu i ich zastosowania w gRPC.

Swift

Element NSError zostaje wywołany ponownie za tripModel(_:didFailUpdateTripWithError:).

// 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

Element NSError zostaje wywołany ponownie za tripModel:didFailUpdateTripWithError:.

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

Zinterpretuj kody stanu

Kody stanu obejmują dwa rodzaje błędów: błędy serwera i sieci oraz po stronie klienta.

Błędy serwera i sieci

Poniższe kody stanu dotyczą błędów sieci lub serwera i nie muszą nic robić. Pakiet SDK klienta automatycznie po takim okresie.

Kod stanuOpis
ANULOWANO Serwer przestał wysyłać odpowiedź. Przyczyną tej sytuacji jest zwykle problem z serwerem.
ANULOWANO Serwer zakończył odpowiedź wychodzącą. To normalne. ma miejsce, gdy
aplikacja jest wysyłana w tle lub po zmianie stanu
Aplikacja dla klientów indywidualnych.
INTERRUPTED
DEADLINE_EXCEEDED Oczekiwanie na odpowiedź serwera trwało zbyt długo.
PRODUKT NIEDOSTĘPNY Serwer był niedostępny. Przyczyną tej sytuacji jest zwykle sieć .

Błędy klienta

Poniższe kody stanu dotyczą błędów klienta i musisz podjąć działania, aby i ją rozwiązać. Pakiet SDK klienta będzie ponawiać próby odświeżenia podróży, dopóki nie aby zakończyć udostępnianie ścieżki, ale nie zostanie ono przywrócone, dopóki nie podejmiesz działań.

Kod stanuOpis
NIEPRAWIDŁOWY_ARG Aplikacja konsumenta podała nieprawidłową nazwę podróży. Nazwa podróży musi musi mieć format providers/{provider_id}/trips/{trip_id}.
NOT_FOUND Podróż nie została utworzona.
PERMISSION_DENIED Aplikacja konsumenta ma niewystarczające uprawnienia. Ten błąd występuje, gdy:
  • Aplikacja konsumenta nie ma uprawnień
  • W projekcie w Google Cloud nie włączono pakietu SDK dla klientów indywidualnych Konsola.
  • Brakuje tokena JWT lub jest on nieprawidłowy.
  • Token JWT jest podpisany za pomocą identyfikatora podróży, który nie pasuje do identyfikatora podróży wybrana podróż.
RESOURCE_EXHAUSTED Limit zasobów wynosi zero lub tempo przepływu ruchu przekracza ograniczenia prędkości.
BEZ UWIERZYTELNIANIA Uwierzytelnianie nie powiodło się z powodu nieprawidłowego tokena JWT. Ten występuje, gdy token JWT jest podpisany bez identyfikatora podróży lub po wygaśnięciu tokena JWT.