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는 서비스 제공업체에 문의하세요
401 UNAUTHENTICATED 유효한 사용자 인증 정보가 없으면 이 오류가 표시됩니다. 예를 들어 JWT 토큰이 이동 ID 또는 JWT 토큰 없이 서명된 경우 만료되었습니다.
403 PERMISSION_DENIED 클라이언트에 충분한 권한이 없는 경우 이 오류가 표시됩니다. (예를 들어 소비자 역할이 있는 사용자가 updateTrip 호출을 시도) JWT 토큰이 유효하지 않거나 API가 클라이언트 프로젝트에 대해 사용 설정되지 않았습니다. JWT 토큰이 누락되었거나 토큰이 요청된 이동 ID와 일치하지 않습니다.
429 RESOURCE_EXHAUSTED 리소스 할당량이 0이거나 트래픽 비율이 한도를 초과합니다.
503 현재 구매할 수 없음 서비스를 사용할 수 없습니다. 전형적인 서버 다운입니다.
504 DEADLINE_EXCEEDED 요청 기한이 지났습니다. 이 오류는 호출자가 이 메서드의 기본 기한 (즉, 서버가 요청을 처리하기에 충분하지 않은 경우) 요청이 기한 내에 완료되지 않았습니다.

소비자 SDK 오류 처리

소비자 SDK가 콜백을 사용하여 소비자 앱에 경로 업데이트 오류를 전송합니다. 메커니즘입니다. 콜백 매개변수는 플랫폼별 반환 유형 ( TripUpdateError 드림 및 NSError (iOS의 경우)

상태 코드 추출

콜백에 전달되는 오류는 일반적으로 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;
    ...
  }
}

상태 코드 해석

상태 코드에는 서버 및 네트워크 관련 오류와 클라이언트 측 오류입니다.

서버 및 네트워크 오류

다음 상태 코드는 네트워크 또는 서버 오류에 대한 것이므로 별도의 조치를 취하지 않아도 됩니다 소비자 SDK는 복구될 수 있습니다

상태 코드설명
ABORTED 서버에서 응답 전송을 중지했습니다. 이 문제는 일반적으로 서버 문제입니다.
CANCELLED 서버가 발신 응답을 종료했습니다. 이것은 일반적으로 일어날 때
백그라운드로 전송되거나 앱의 상태 변경이 있을 때
소비자 앱
INTERRUPTED
DEADLINE_EXCEEDED 서버가 응답하는 데 시간이 너무 오래 걸립니다.
현재 구매할 수 없음 서버를 사용할 수 없습니다. 이 문제는 일반적으로 네트워크 또는 있습니다.

클라이언트 오류

다음 상태 코드는 클라이언트 오류용이며 해결할 수 있습니다 소비자 SDK는 탐색 여정 공유가 종료되지만 사용자가 조치를 취하기 전에는 복구되지 않습니다

상태 코드설명
INVALID_ARGUMENT 소비자 앱에서 잘못된 경로 이름을 지정했습니다. 이동 이름은 providers/{provider_id}/trips/{trip_id} 형식을 따라야 합니다.
NOT_FOUND 이동이 생성되지 않았습니다.
PERMISSION_DENIED 소비자 앱의 권한이 충분하지 않습니다. 이 오류는 다음과 같은 경우에 발생합니다.
  • 소비자 앱에 권한이 없음
  • Google Cloud의 프로젝트에 소비자 SDK가 사용 설정되지 않았습니다. 콘솔을 클릭합니다.
  • JWT 토큰이 누락되었거나 잘못되었습니다.
  • JWT 토큰이 요청한 여정입니다.
RESOURCE_EXHAUSTED 리소스 할당량이 0이거나 트래픽 흐름 속도가 속도를 제한합니다.
UNAUTHENTICATED 잘못된 JWT 토큰으로 인해 요청 인증에 실패했습니다. 이 JWT 토큰이 이동 ID 없이 서명된 경우 오류가 발생합니다. JWT 토큰 만료 시