在 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 但出现错误,您可以获取回调 通过实现 delegate 方法实现 tripModel tripModel(_:didFailUpdateTripWithError:)。错误 消息符合 Google Cloud Error 标准。如需了解详细错误 请查看消息定义和所有错误代码, Google Cloud 错误文档

以下是行程监控期间可能发生的一些常见错误:

HTTP RPC 说明
400 INVALID_ARGUMENT 客户指定的行程名称无效。行程名称必须遵循 格式为 providers/{provider_id}/trips/{trip_id}。通过 provider_id 必须是所有者为 Cloud 的 Cloud 项目的 ID, 服务提供商
401 UNAUTHENTICATED 如果没有有效的身份验证凭据,您会收到此错误。 例如,在 JWT 令牌签名时不含行程 ID 或 JWT 令牌 已过期。
403 PERMISSION_DENIED 如果客户端权限不足,您会收到此错误 (例如,具有使用方角色的用户尝试调用 updateTrip),如果 JWT 令牌无效,或者客户端项目未启用该 API。 可能缺少 JWT 令牌,或者令牌已用行程 ID 签名, 与请求的行程 ID 不匹配。
429 RESOURCE_EXHAUSTED 资源配额为零或流量超出限制。
503 UNAVAILABLE 服务不可用。通常是服务器已关闭。
504 DEADLINE_EXCEEDED 超出请求时限。只有在调用方设置了 比方法的默认截止期限短(即 请求的截止时间不足以让服务器处理请求)且 请求未在期限内完成。

处理使用方 SDK 错误

消费者 SDK 使用回调向消费者应用发送行程更新错误 机制。回调参数是平台特定的返回值类型 ( TripUpdateError 以及 NSError )。

提取状态代码

传递给回调函数的错误通常是 gRPC 错误,您也可以 从它们提取额外信息。对于 状态代码的完整列表,请参阅 状态代码及其在 gRPC 中的使用

Swift

系统会在 tripModel(_:didFailUpdateTripWithError:) 中回调 NSError

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

系统会在 tripModel:didFailUpdateTripWithError: 中回调 NSError

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

解读状态代码

状态代码涵盖两种错误:与服务器和网络相关的错误,以及 错误。

服务器和网络连接错误

以下状态代码针对的是网络错误或服务器错误, 无需采取任何措施来解决这些问题。使用方 SDK 会自动 能够从中恢复

状态代码说明
ABORTED 服务器已停止发送响应。这通常是由 服务器问题。
已取消 服务器终止了外发响应。这通常 发生以下情况:
当应用被发送到后台时,或者当
消费者应用。
INTERRUPTED
DEADLINE_EXCEEDED 服务器响应时间过长。
UNAVAILABLE 服务器不可用。这通常是由网络所致 问题。

客户端错误

以下状态代码针对的是客户端错误,您必须采取措施 并加以解决。Consumer SDK 会继续重新尝试刷新行程,直到您 结束旅程分享,但在您采取行动后才能恢复。

状态代码说明
INVALID_ARGUMENT 消费者应用指定的行程名称无效;行程名称必须 请遵循 providers/{provider_id}/trips/{trip_id} 格式。
NOT_FOUND 此行程从未创建。
PERMISSION_DENIED 消费者应用的权限不足。出现此错误的情况包括:
  • 消费者应用没有权限
  • Google Cloud 中的项目未启用使用方 SDK 控制台。
  • JWT 令牌缺失或无效。
  • JWT 令牌的签名行程 ID 与 请求的行程。
RESOURCE_EXHAUSTED 资源配额为零,或者流量的速率超过 限速。
UNAUTHENTICATED 由于 JWT 令牌无效,请求未通过身份验证。这个 如果 JWT 令牌签名时不含行程 ID,则会发生错误;或者 在 JWT 令牌过期时触发。