iOS でルートをフォローする

プラットフォームを選択: Android iOS JavaScript

ルートを追跡すると、一般ユーザー向けアプリに 適切な車両を判断できますそのためには、まず ルートのフォロー、ルートの進捗状況の更新、ルートのフォローの停止 表示されます。

このドキュメントでは、そのプロセスについて説明します。

ルートのフォローを開始する

旅程の共有を使用してルートをフォローする方法は次のとおりです。

  • 降車場所や乗車場所などのすべてのユーザー入力を収集する ViewController から。

  • ジャーニーを直接共有するには、新しい ViewController を作成してください。

次の例は、トレーニングの直後にジャーニーの共有を開始する方法を示しています。 ビューが読み込まれます。

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

ルートのフォローを停止する

ルートのフォローは完了するかキャンセルされると停止します。次の サンプルは、アクティブなルートの共有を停止する方法を示しています。

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

移動状況を更新

ルートの進行中は、ルートの進捗状況を次のように管理します。

ルートが完了した場合やルートがキャンセルされた場合は、最新情報のリッスンを停止します。 例については以下をご覧ください。 更新のリッスンを停止する例

更新のリッスンを開始する例

次の例は、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];
  ...
}

更新のリッスン停止の例

次の例は、tripModel の登録をキャンセルする方法を示しています。 呼び出すことができます。

Swift

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

Objective-C

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

ルート更新情報を処理する例

次の例は、GMTCTripModelSubscriber を実装する方法を示しています。 ルート状態が更新されたときにコールバックを処理するためのプロトコルです。

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

ルートエラーを処理する

tripModel をサブスクライブしていてエラーが発生した場合は、 デリゲート メソッドを実装して tripModel を初期化 tripModel(_:didFailUpdateTripWithError:)。エラー Google Cloud のエラー標準に従います。詳細なエラーの場合 すべてのエラーコードについては、このモジュールの Google Cloud のエラーのドキュメント

ルートのモニタリング中に発生する可能性のある一般的なエラーは次のとおりです。

HTTP RPC 説明
400 INVALID_ARGUMENT クライアントが無効なルート名を指定しました。旅行名は 形式は providers/{provider_id}/trips/{trip_id} です。「 provider_id は、プロジェクトが所有する Cloud プロジェクトの ID です。 サービスプロバイダによって異なります
401 UNAUTHENTICATED このエラーは、有効な認証情報がない場合に表示されます。 たとえば、JWT トークンがルート ID や JWT トークンなしで署名されている場合など の有効期限が切れています。
403 PERMISSION_DENIED このエラーは、クライアントに十分な権限がない場合に表示されます。 (たとえば、コンシューマ ロールを持つユーザーが updateTrip を呼び出そうとした場合)は、 JWT トークンが無効か、クライアント プロジェクトで API が有効になっていません。 JWT トークンがないか、トークンが はリクエストされたルート ID と一致しません。
429 RESOURCE_EXHAUSTED リソースの割り当てがゼロであるか、トラフィックのレートが上限を超えています。
503 UNAVAILABLE サービス利用不可。通常、サーバーがダウンしています。
504 DEADLINE_EXCEEDED リクエスト期限を超えました。このエラーは、呼び出し元が メソッドのデフォルトの期限(つまり、 サーバーがリクエストを処理するには、要求された期限では足りません)。 期限内にリクエストが完了しませんでした。

コンシューマ SDK エラーの処理

Consumer SDK がコールバックを使用して、ルート更新情報のエラーをユーザーアプリに送信します。 メカニズムです。コールバック パラメータはプラットフォーム固有の戻り値の型( TripUpdateErrorNSError

ステータス コードを抽出する

通常、コールバックに渡されるエラーは gRPC エラーですが、 ステータス コードの形式で追加情報を抽出します。対象: ステータス コードの完全なリストについては、 ステータス コードと gRPC での使用

Swift

NSErrortripModel(_: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

NSErrortripModel: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;
    ...
  }
}

ステータス コードを解釈する

ステータス コードは、サーバーおよびネットワーク関連のエラーと、 クライアントサイドのエラーです。

サーバー エラーとネットワーク エラー

次のステータス コードは、ネットワーク エラーまたはサーバー エラーを示すものです。 解決のための対応は不要ですConsumer SDK が自動的に 復元します。

ステータス コード説明
ABORTED サーバーがレスポンスの送信を停止しました。この問題は通常 発生します。
CANCELLED サーバーが送信レスポンスを終了しました。これは通常 次の場合に起こります。
アプリがバックグラウンドに送られたときや、テーブルで状態が変化したときに
ユーザーアプリ。
INTERRUPTED
DEADLINE_EXCEEDED サーバーの応答に時間がかかりすぎました。
UNAVAILABLE サーバーにアクセスできませんでした。これは通常、ネットワークや 困難です。

クライアントエラー

次のステータス コードはクライアント エラーを示します。 解決できます。Consumer SDK がルートの更新を再試行し続けます。 履歴の共有は終了しますが 復元はできません

ステータス コード説明
INVALID_ARGUMENT ユーザー アプリが指定したルート名が無効です。旅行名は providers/{provider_id}/trips/{trip_id} の形式を使用します。
NOT_FOUND ルートが作成されない。
PERMISSION_DENIED ユーザー アプリに十分な権限がありません。このエラーは、次の場合に発生します。
  • ユーザー アプリに権限がない
  • Google Cloud のプロジェクトで Consumer SDK が有効になっていない できます。
  • JWT トークンがないか、無効です。
  • JWT トークンが、一致していないルート ID で署名されています。 ルートが表示されます。
RESOURCE_EXHAUSTED リソース割り当てがゼロであるか、トラフィック フローのレートが 制限します。
UNAUTHENTICATED JWT トークンが無効なため、リクエストが認証に失敗しました。この JWT トークンがルート ID なしで署名された場合、または JWT トークンの有効期限が切れたとき。