탑승을 팔로우하면 소비자 앱에 적절한 차량의 위치가 소비자에게 표시됩니다. 이렇게 하려면 앱에서 탑승 팔로우를 시작하고 탑승 진행률을 업데이트하며 탑승이 완료되면 탑승 팔로우를 중지해야 합니다.
이 문서에서는 이 프로세스의 작동 방식을 설명합니다.
탑승 팔로우 시작
탑승 팔로우를 시작하는 방법은 다음과 같습니다.
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(_:didFailUpdateTripWithError:)을 구현하여 tripModel의 콜백
을 가져올 수 있습니다. 오류 메시지는 Google Cloud 오류 표준을 따릅니다. 자세한 오류
메시지 정의 및 모든 오류 코드는
Google Cloud 오류 문서를 참고하세요.
다음은 탑승 모니터링 중에 발생할 수 있는 몇 가지 일반적인 오류입니다.
| HTTP | RPC | 설명 |
|---|---|---|
| 400 | INVALID_ARGUMENT | 클라이언트가 잘못된 탑승 이름을 지정했습니다. 탑승 이름은
형식 providers/{provider_id}/trips/{trip_id}을 따라야 합니다.
provider_id 는
서비스 제공업체가 소유한 Cloud 프로젝트의 ID여야 합니다. |
| 401 | UNAUTHENTICATED | 유효한 사용자 인증 정보가 없으면 이 오류가 발생합니다. 예를 들어 탑승 ID 없이 JWT 토큰이 서명되거나 JWT 토큰 이 만료된 경우입니다. |
| 403 | PERMISSION_DENIED | 클라이언트에게 충분한 권한이 없거나 (예: 소비자 역할의 사용자가 updateTrip을 호출하려고 함), JWT 토큰이 유효하지 않거나, 클라이언트 프로젝트에 API가 사용 설정되지 않은 경우 이 오류가 발생합니다. JWT 토큰이 누락되었거나 토큰이 요청된 탑승 ID와 일치하지 않는 탑승 ID로 서명되었을 수 있습니다. |
| 429 | RESOURCE_EXHAUSTED | 리소스 할당량이 0이거나 트래픽 비율이 한도를 초과합니다. |
| 503 | UNAVAILABLE | 서비스를 사용할 수 없습니다. 전형적인 서버 다운입니다. |
| 504 | DEADLINE_EXCEEDED | 요청 기한이 지났습니다. 이 오류는 호출자가 메서드의 기본 기한보다 짧게 기한을 설정한 후 (서버가 요청을 처리할 수 있을 만큼 기한이 충분히 길지 않아서) 요청이 기한 내에 완료되지 않았을 때만 발생합니다. |
Consumer SDK 오류 처리
Consumer SDK는 콜백 메커니즘을 사용하여 탑승 업데이트 오류를 소비자 앱으로 보냅니다. 콜백 매개변수는 플랫폼별 반환 유형입니다(
TripUpdateError
Android의 경우, NSError
iOS의 경우).
상태 코드 추출
콜백에 전달되는 오류는 일반적으로 gRPC 오류이며 상태 코드 형식으로 추가 정보를 추출할 수도 있습니다. 상태 코드의 전체 목록은 gRPC의 상태 코드 및 사용을 참고하세요.
Swift
NSError는 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
NSError는 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;
...
}
}
상태 코드 해석
상태 코드는 서버 및 네트워크 관련 오류와 클라이언트 측 오류라는 두 가지 유형의 오류를 다룹니다.
서버 및 네트워크 오류
다음 상태 코드는 네트워크 또는 서버 오류에 해당하며 이를 해결하기 위해 조치를 취할 필요가 없습니다. Consumer SDK는 자동으로 복구됩니다.
| 상태 코드 | 설명 |
|---|---|
| ABORTED | 서버가 응답 전송을 중지했습니다. 일반적으로 서버 문제로 인해 발생합니다. |
| CANCELLED | 서버가 나가는 응답을 종료했습니다. 일반적으로 앱이 백그라운드로 전송되거나
소비자 앱의 상태가 변경될 때 발생합니다. |
| INTERRUPTED | |
| DEADLINE_EXCEEDED | 서버가 응답하는 데 시간이 너무 오래 걸립니다. |
| UNAVAILABLE | 서버를 사용할 수 없습니다. 일반적으로 네트워크 문제로 인해 발생합니다. |
클라이언트 오류
다음 상태 코드는 클라이언트 오류에 해당하며 이를 해결하기 위해 조치를 취해야 합니다. Consumer SDK는 여정 공유를 종료할 때까지 탑승 새로고침을 계속 재시도하지만 조치를 취할 때까지 복구되지 않습니다.
| 상태 코드 | 설명 |
|---|---|
| INVALID_ARGUMENT | Consumer 앱에서 잘못된 탑승 이름을 지정했습니다. 탑승 이름은
providers/{provider_id}/trips/{trip_id} 형식을 따라야 합니다.
|
| NOT_FOUND | 탑승이 생성되지 않았습니다. |
| PERMISSION_DENIED | 소비자 앱에 권한이 충분하지 않습니다. 이 오류는 다음과 같은 경우에 발생합니다.
|
| RESOURCE_EXHAUSTED | 리소스 할당량이 0이거나 트래픽 흐름 비율이 속도 제한을 초과합니다. |
| UNAUTHENTICATED | 잘못된 JWT 토큰으로 인해 요청 인증에 실패했습니다. 이 오류는 JWT 토큰이 탑승 ID 없이 서명되거나 JWT 토큰이 만료된 경우에 발생합니다. |