소비자 SDK를 사용하여 주문형 차량 공유 및 배송 솔루션 백엔드 서비스와 통합된 기본 소비자 앱을 빌드하고 실행할 수 있습니다. 활성 경로를 표시하고, 이동 업데이트에 응답하고, 이동 오류를 처리할 수 있는 이동 및 주문 진행 상황 앱을 만들 수 있습니다.
소비자 SDK에는 모듈식 아키텍처가 있으므로 특정 앱에 사용할 API 부분을 사용하고 자체 API, Fleet Engine에서 제공하는 백엔드 서비스, Google Maps Platform의 추가 API와 통합할 수 있습니다.
최소 시스템 요구사항
프로젝트 구성
CocoaPods를 사용하여 소비자 SDK를 구성할 수 있습니다.
CocoaPods 사용
CocoaPods를 사용하여 소비자 SDK를 구성하려면 다음 항목이 필요합니다.
CocoaPods 도구: 이 도구를 설치하려면 터미널을 열고 다음 명령어를 실행합니다.
sudo gem install cocoapods
자세한 내용은 CocoaPods 시작 가이드를 참고하세요.
Google 액세스 목록의 개발 계정 SDK의 포드 저장소가 공개 소스가 아닙니다. 포드에 액세스하려면 Google 고객 엔지니어에게 문의하세요. 엔지니어가 액세스 계정을 개발 목록에 추가하고 인증을 위해 쿠키를 설정합니다.
프로젝트가 액세스 목록에 추가되면 포드에 액세스할 수 있습니다.
소비자 SDK용 Podfile을 만들고 이를 사용하여 API와 종속 항목을 설치합니다. 먼저 프로젝트 디렉터리에 Podfile이라는 파일을 만듭니다. 이 파일은 프로젝트의 종속 항목을 정의합니다. 그런 다음 Podfile을 수정하고 종속 항목을 추가합니다. 다음은 종속 항목이 포함된 예입니다.
source "https://cpdc-eap.googlesource.com/ridesharing-consumer-sdk" source "https://github.com/CocoaPods/Specs.git" target 'YOUR_APPLICATION_TARGET_NAME_HERE' do pod 'GoogleRidesharingConsumer' end
Podfile을 저장합니다. 터미널을 열고 Podfile이 포함된 디렉터리로 이동합니다.
cd <path-to-project>
포드 설치 명령어를 실행합니다. 이렇게 하면 Podfile에 지정된 API가 포함된 종속 항목과 함께 설치됩니다.
pod install
Xcode를 닫은 다음 프로젝트의 .xcworkspace 파일을 (더블클릭) 열어 Xcode를 실행합니다. 나중에 프로젝트를 열려면 .xcworkspace 파일을 사용하세요.
XCFramework 설치
XCFramework는 소비자 SDK를 설치하는 데 사용하는 바이너리 패키지입니다. 이 패키지는 M1 칩셋을 사용하는 머신을 포함하여 여러 플랫폼에서 사용할 수 있습니다. 이 가이드에서는 프로젝트에 소비자 SDK가 포함된 XCFramework를 수동으로 추가하고 Xcode에서 빌드 설정을 구성하는 방법을 보여줍니다.
Google에서 받은 소스 파일의 압축을 풉니다.
Xcode를 시작하고 기존 프로젝트를 열거나 새 프로젝트를 만듭니다. iOS를 처음 사용하는 경우 새 프로젝트를 만들고 iOS 앱 템플릿을 선택합니다.
프로젝트 그룹이 없는 경우 프로젝트 그룹에 프레임워크 그룹을 만듭니다.
XCFramework가 포함된 ZIP 파일의
Resources
디렉터리에 포함된gRPCCertificates.bundle
파일을 Xcode 프로젝트의 최상위 디렉터리로 드래그합니다. 메시지가 표시되면 필요한 경우 항목 복사를 선택합니다.소비자 SDK를 설치하려면
GoogleRidesharingConsumer.xcframework
파일을Frameworks, Libraries, and Embedded Content
아래의 프로젝트로 드래그합니다. 메시지가 표시되면 필요한 경우 항목 복사를 선택합니다.프로젝트 탐색기에서 프로젝트를 선택하고 애플리케이션의 대상을 고릅니다.
Build Phases(빌드 단계) 탭을 열고 Link Binary with Libraries(라이브러리와 바이너리 연결)에서 아직 없는 프레임워크와 라이브러리를 추가합니다.
Accelerate.framework
CoreData.framework
CoreGraphics.framework
CoreImage.framework
CoreLocation.framework
CoreTelephony.framework
CoreText.framework
GLKit.framework
ImageIO.framework
libc++.tbd
libz.tbd
Metal.framework
OpenGLES.framework
QuartzCore.framework
SystemConfiguration.framework
UIKit.framework
특정 대상 대신 자신의 프로젝트를 선택하고 빌드 설정 탭을 엽니다. 기타 링커 플래그 섹션에서 디버그 및 릴리스 모두에
‑ObjC
를 추가합니다. 이러한 설정이 표시되지 않으면 빌드 설정 표시줄의 필터를 기본에서 모두로 변경합니다.
애플리케이션 통합
인증 토큰 제공
소비자 앱이 Fleet Engine에 경로 업데이트를 요청하면 요청에 유효한 액세스 토큰이 포함되어야 합니다. 이러한 요청을 승인하고 인증하기 위해 소비자 SDK는 GMTCAuthorization
프로토콜을 준수하는 객체를 호출합니다. 객체는 필요한 액세스 토큰을 제공하는 역할을 합니다.
앱 개발자는 토큰이 생성되는 방식을 선택할 수 있습니다. 구현에서는 다음을 실행할 수 있는 기능을 제공해야 합니다.
- HTTPS 서버에서 JSON 형식의 액세스 토큰을 가져옵니다.
- 토큰을 파싱하고 캐시합니다.
- 토큰이 만료되면 토큰을 갱신합니다.
Fleet Engine 서버에서 예상하는 토큰에 대한 자세한 내용은 승인을 위한 JSON 웹 토큰 (JWT) 만들기를 참조하세요.
제공업체 ID는 Google Cloud 프로젝트 ID와 동일합니다. 자세한 내용은 Fleet Engine 시작하기를 참고하세요.
다음 예시에서는 액세스 토큰 제공자를 구현합니다.
Swift
/*
* SampleAccessTokenProvider.swift
*/
import GoogleRidesharingConsumer
private let providerURL = "INSERT_YOUR_TOKEN_PROVIDER_URL"
class SampleAccessTokenProvider: NSObject, GMTCAuthorization {
private struct AuthToken {
// The cached trip token.
let token: String
// Keep track of when the token expires for caching.
let expiration: TimeInterval
// Keep track of the trip ID the cached token is for.
let tripID: String
}
enum AccessTokenError: Error {
case missingAuthorizationContext
case missingData
}
private var authToken: AuthToken?
func fetchToken(
with authorizationContext: GMTCAuthorizationContext?,
completion: @escaping GMTCAuthTokenFetchCompletionHandler
) {
// Get the trip ID from the authorizationContext. This is set by the Consumer SDK.
guard let authorizationContext = authorizationContext else {
completion(nil, AccessTokenError.missingAuthorizationContext)
return
}
let tripID = authorizationContext.tripID
// If appropriate, use the cached token.
if let authToken = authToken,
authToken.expiration > Date.now.timeIntervalSince1970 && authToken.tripID == tripID
{
completion(authToken.token, nil)
return
}
// Otherwise, try to fetch a new token from your server.
let request = URLRequest(url: URL(string: providerURL))
let task = URLSession.shared.dataTask(with: request) { [weak self] data, _, error in
guard let strongSelf = self else { return }
guard error == nil else {
completion(nil, error)
return
}
// Replace the following key values with the appropriate keys based on your
// server's expected response.
let tripTokenKey = "TRIP_TOKEN_KEY"
let tokenExpirationKey = "TOKEN_EXPIRATION"
guard let data = data,
let fetchData = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let token = fetchData[tripTokenKey] as? String,
let expiration = fetchData[tokenExpirationKey] as? Double
else {
completion(nil, AccessTokenError.missingData)
return
}
strongSelf.authToken = AuthToken(token: token, expiration: expiration, tripID: tripID)
completion(token, nil)
}
task.resume()
}
}
Objective-C
/*
* SampleAccessTokenProvider.h
*/
#import <Foundation/Foundation.h>
#import <GoogleRidesharingConsumer/GoogleRidesharingConsumer.h>
NS_ASSUME_NONNULL_BEGIN
@interface SampleAccessTokenProvider : NSObject <GMTCAuthorization>
@end
NS_ASSUME_NONNULL_END
/*
* SampleAccessTokenProvider.m
*/
#import "SampleAccessTokenProvider.h"
#import "GoogleRidesharingConsumer/GoogleRidesharingConsumer.h"
static NSString *const PROVIDER_URL = @"INSERT_YOUR_TOKEN_PROVIDER_URL";
// SampleAccessTokenProvider.m
@implementation SampleAccessTokenProvider {
// The cached token with claims to the current trip.
NSString *_cachedTripToken;
// Keep track of the Trip ID the cached token is for.
NSString *_lastKnownTripID;
// Keep track of when tokens expire for caching.
NSTimeInterval _tokenExpiration;
}
- (void)fetchTokenWithContext:(nullable GMTCAuthorizationContext *)authorizationContext
completion:(nonnull GMTCAuthTokenFetchCompletionHandler)completion {
// Get the trip ID from the authorizationContext. This is set by the Consumer SDK.
NSString *tripID = authorizationContext.tripID;
// Clear cached trip token if trip ID has changed.
if (![_lastKnownTripID isEqual:tripID]) {
_tokenExpiration = 0.0;
_cachedTripToken = nil;
}
_lastKnownTripID = tripID;
// Clear cached tripToken if it has expired.
if ([[NSDate date] timeIntervalSince1970] > _tokenExpiration) {
_cachedTripToken = nil;
}
// If appropriate, use the cached token.
if (_cachedTripToken) {
completion(_cachedTripToken, nil);
return;
}
// Otherwise, try to fetch a new token from your server.
NSURL *requestURL = [NSURL URLWithString:PROVIDER_URL];
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:requestURL];
request.HTTPMethod = @"GET";
// Replace the following key values with the appropriate keys based on your
// server's expected response.
NSString *tripTokenKey = @"TRIP_TOKEN_KEY";
NSString *tokenExpirationKey = @"TOKEN_EXPIRATION";
__weak typeof(self) weakSelf = self;
void (^handler)(NSData *_Nullable data, NSURLResponse *_Nullable response,
NSError *_Nullable error) =
^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError *_Nullable error) {
typeof(self) strongSelf = weakSelf;
if (error) {
completion(nil, error);
return;
}
NSError *JSONError;
NSMutableDictionary *JSONResponse =
[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&JSONError];
if (JSONError) {
completion(nil, JSONError);
return;
} else {
// Sample code only. No validation logic.
id expirationData = JSONResponse[tokenExpirationKey];
if ([expirationData isKindOfClass:[NSNumber class]]) {
NSTimeInterval expirationTime = ((NSNumber *)expirationData).doubleValue;
strongSelf->_tokenExpiration = [[NSDate date] timeIntervalSince1970] + expirationTime;
}
strongSelf->_cachedTripToken = JSONResponse[tripTokenKey];
completion(JSONResponse[tripTokenKey], nil);
}
};
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *mainQueueURLSession =
[NSURLSession sessionWithConfiguration:config delegate:nil
delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *task = [mainQueueURLSession dataTaskWithRequest:request completionHandler:handler];
[task resume];
}
@end
애플리케이션 초기화
Swift
/*
* AppDelegate.swift
*/
import GoogleRidesharingConsumer
import GoogleMaps
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Register your API key for GMSServices.
GMSServices.provideAPIKey(yourMapsAPIKey)
// Set the instance of the SampleAccessTokenProvider.
GMTCServices.setAccessTokenProvider(SampleAccessTokenProvider(), providerID: yourProviderID)
// Other initialization code ...
return true
}
}
Objective-C
/*
* AppDelegate.m
*/
#import <GoogleMaps/GoogleMaps.h>
#import <GoogleRidesharingConsumer/GoogleRidesharingConsumer.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//Register your API key for GMSServices.
[GMSServices provideAPIKey:yourMapsAPIKey];
//Set the instance of the AccessTokenFactory.
[GMTCServices setAccessTokenProvider:[[SampleAccessTokenProvider alloc] init]
providerID:yourProviderID];
// Other initialization code ...
return YES;
}
@end
지도 보기 통합
지도뷰 초기화
다음 예는 GMTCMapView
를 초기화하는 방법을 보여줍니다.
Swift
/*
* MapViewController.swift
*/
class ViewController: UIViewController, GMTCMapViewDelegate {
private var rideSharingMap: GMTCMapView?
override func viewDidLoad() {
super.viewDidLoad()
self.rideSharingMap = GMTCMapView(frame: UIScreen.main.bounds)
self.rideSharingMap.delegate = self
self.rideSharingMap?.settings.myLocationButton = true
self.view.addSubview(self.rideSharingMap!)
...
}
Objective-C
/*
* MapViewController.h
*/
@interface MapViewController : UIViewController<GMTCMapViewDelegate>
...
@end
/*
* MapViewController.m
*/
@implementation MapViewController
- (void)viewDidLoad {
[super viewDidLoad];
...
self.mapView = [[GMTCMapView alloc] init];
self.mapView.settings.myLocationButton = YES;
self.mapView.delegate = self;
...
}
...
@end
지도뷰 이벤트 처리
다음 예에서는 고객 상태 이벤트를 처리하는 대리자를 구현하는 방법을 보여줍니다.
Swift
func mapViewDidInitialize(_ mapview: GMTCMapView) {
// Handle the update to the state of the map view to browsing.
}
func mapView(_ mapView: GMSMapView, didTapConsumerMarker mapMarker: GMSMarker, markerType: GMTCMapViewMarkerType) -> Bool {
// Handle the mapView marker was tapped.
}
Objective-C
/*
* MapViewController.m
*/
#pragma mark - GMTCMapViewDelegate implementation
// Handle state update of map view.
- (void)mapViewDidInitializeCustomerState:(GMTCMapView *)mapview {
// Handle the update to the state of the map view to browsing.
}
- (void)mapView:(GMSMapView *)mapView
didTapConsumerMarker:(nonnull GMSMarker *)mapMarker
markerType:(GMTCMapViewMarkerType)markerType {
// Handle the mapView marker was tapped.
}
여정 공유
뷰가 로드되면 새 경로를 시작합니다.
다음 예에서는 뷰가 로드된 직후 여정 공유를 시작하는 방법을 보여줍니다. 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] init];
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의 콜백을 가져올 수 있습니다. Fleet Engine은 Google Cloud 오류 표준을 따르는 오류 메시지를 생성했습니다. 자세한 오류 메시지 정의와 모든 오류 코드는 Google Cloud 오류 문서를 참조하세요.
특히 이동 모니터링의 경우 유효한 인증 토큰을 제공해야 합니다. 토큰 만료 등 유효한 사용자 인증 정보가 없으면 401 UNAUTHENTICATED
가 발생합니다.403 PERMISSION_DENIED
는 호출자에게 특정 API 호출 권한이 없거나 (예: 소비자 역할이 있는 사용자가 updateTrip을 호출하려고 함) 요청에 JWT 토큰에 유효한 car_id/trip_id가 없으면 발생합니다.
자세한 내용은 소비자 SDK 오류 처리를 참조하세요.
UI 맞춤설정
맞춤 다중선 UI 옵션 가져오기/설정
다음 예에서는 다중선에 맞춤 UI 옵션을 설정하는 방법을 보여줍니다.
Swift
/** MapViewController.swift */
func updatePolylineUIOptions() {
// The polyline type that you would like to set custom UI options for.
let customizablePolylineType = GMTCPolylineType.activeRoute
let polylineStyleOptions = GMTCMutablePolylineStyleOptions()
polylineStyleOptions.strokeWidth = 8.0
polylineStyleOptions.strokeColor = .blue
polylineStyleOptions.isVisible = true
polylineStyleOptions.zIndex = 1000
polylineStyleOptions.isGeodesic = true
let coordinator = self.mapView.consumerMapStyleCoordinator
coordinator.setPolylineStyleOptions(polylineStyleOptions, polylineType:customizablePolylineType)
}
Objective-C
/** MapViewController.m */
- (void)updatePolylineUIOptions {
// The polyline type that you would like to set custom UI options for.
GMTCPolylineType customizablePolylineType = GMTCPolylineTypeActiveRoute;
GMTCMutablePolylineStyleOptions *polylineStyleOptions =
[[GMTCMutablePolylineStyleOptions alloc] init];
polylineStyleOptions.strokeWidth = 8.0;
polylineStyleOptions.strokeColor = [UIColor blueColor];
polylineStyleOptions.isVisible = YES;
polylineStyleOptions.zIndex = 1000;
polylineStyleOptions.isGeodesic = YES;
[[_mapView consumerMapStyleCoordinator] setPolylineStyleOptions:polylineStyleOptions
polylineType:customizablePolylineType];
}
맞춤 마커 UI 옵션 가져오기/설정
다음 예에서는 마커의 맞춤 UI 옵션을 설정하는 방법을 보여줍니다.
Swift
/** MapViewController.swift */
func updateMarkerUIOptions() {
let customizableMarkerType = GMTCCustomizableMarkerType.tripVehicle
let markerStyleOptions = GMTCMutableMarkerStyleOptions()
markerStyleOptions.groundAnchor = groundAnchor
markerStyleOptions.isVisible = true
markerStyleOptions.icon = icon
markerStyleOptions.zIndex = 100
markerStyleOptions.isFlat = false
let coordinator = self.mapView.consumerMapStyleCoordinator
coordinator.setMarkerStyleOptions(markerStyleOptions, markerType: customizableMarkerType)
}
Objective-C
/** MapViewController.m */
- (void)updateMarkerUIOptions {
// The marker type that you would like to set custom UI options for.
GMTCCustomizableMarkerType customizableMarkerType = GMTCCustomizableMarkerTypeTripVehicle;
GMTCMutableMarkerStyleOptions *markerStyleOptions =
[[GMTCMutableMarkerStyleOptions alloc] init];
markerStyleOptions.groundAnchor = groundAnchor;
markerStyleOptions.isVisible = YES;
markerStyleOptions.icon = icon;
markerStyleOptions.zIndex = 100;
markerStyleOptions.isFlat = NO;
[[_mapView consumerMapStyleCoordinator] setMarkerStyleOptions:markerStyleOptions markerType:customizableMarkerType];
}
카메라 확대/축소 조정하기
iOS용 Maps SDK의 내 위치 버튼은 기기 위치를 중심으로 카메라를 설정합니다.
활성 탐색 여정 공유 세션이 있는 경우 기기 위치만 중심이 아닌 여정에 초점을 맞출 수 있도록 카메라를 중앙에 배치할 수 있습니다.
소비자 SDK는 기본적으로 사용 설정되는 자동차 카메라 기능을 제공합니다. 카메라를 확대하여 여정 공유 경로 및 다음 경로 경유지에 중점을 둡니다.
카메라 동작을 더 세밀하게 제어해야 하면 isAllowCameraAutoUpdate
속성을 사용하여 자동 카메라 기능을 사용 중지하거나 사용 설정하면 됩니다.
카메라 맞춤설정에 관한 자세한 내용은 iOS용 Maps SDK 카메라 이동을 참고하세요.