iOS için Tüketici SDK'sını Kullanmaya Başlama

Temel bir kod oluşturmak ve çalıştırmak için İsteğe Bağlı Yolculuklar ve Teslimatlar Çözümü arka uç hizmetleriyle entegre edilmiş tüketici uygulaması. Şunları yapabilirsiniz: aktif bir geziyi görüntüleyebilecek bir Gezi ve Sipariş İlerlemesi uygulaması ve gezi güncellemelerini yapın.

Tüketici SDK'sının modüler bir mimarisi olduğundan API'nın belirli bir uygulama için kullanmak istediğiniz kısımlarını kullanabilir ve bunları Filo tarafından sağlanan arka uç hizmetleriyle kendi API'lerinizle entegre edin Google Haritalar Platformu'nun ek API'leri ve diğer API'leri dahil edilir.

Minimum sistem gereksinimleri

  • Mobil cihazda iOS 14 veya daha yeni bir sürüm yüklü olmalıdır.
  • X kodu sürüm 15 veya sonraki bir sürüme sahip olmanız gerekir.
  • Proje yapılandırması

    Swift Paket Yöneticisi

    Tüketici SDK'sı aracılığıyla yüklenebilir Swift Package Manager'a dokunun. SDK'yı eklemek için mevcut Tüketici SDK'sı bağımlılıklarını kaldırın.

    SDK'yı yeni veya mevcut bir projeye eklemek için aşağıdaki adımları uygulayın:

    1. Xcode project veya workspace dosyanızı açın, ardından Dosya > Paket Bağımlılıkları Ekleyin.
    2. URL olarak https://github.com/googlemaps/ios-consumer-sdk adresini girip Enter'a basın. paketi çekin ve "Paket Ekle"yi tıklayın.
    3. Belirli bir version yüklemek için Bağımlılık Kuralı alanını sürüm temelli seçeneklerdir. Yeni projeler için en son sürümü ve "Tam Sürüm"ü kullanarak seçeneğini belirleyin. İşlem tamamlandığında "Paket Ekle"yi tıklayın.
    4. Paket Ürünlerini Seçin penceresinde, GoogleRidesharingConsumer öğesinin şuraya ekleneceğini doğrulayın: belirlediğiniz main hedefidir. İşlem tamamlandığında "Paket Ekle"yi tıklayın.
    5. Yüklemenizi doğrulamak için hedefinizin General bölmesine gidin. Çerçeveler, Kitaplıklar ve Yerleştirilmiş İçerikler bölümünde yüklü paketleri göreceksiniz. "Paket Bağımlılıkları"nı da görüntüleyebilirsiniz “Project Navigator”ın bölümü .

    Mevcut bir projenin package öğesini güncellemek için şu adımları izleyin:

    1. 9.0.0'dan önceki bir sürümden yeni sürüme geçiyorsanız şunları kaldırmanız gerekir: şu bağımlılıklar: GoogleMapsBase, GoogleMapsCore ve Yükseltme işleminden sonra GoogleMapsM4B. Bağımlılığı kaldırmayın: GoogleMaps Daha fazla bilgi için Sürüm 9.0.0 Sürüm Notları.

      Xcode proje yapılandırma ayarlarınızdan Çerçeveler, Kitaplıklar, ve yerleştirilmiş içerik gibi diğer özelliklerden de faydalanabilirsiniz. Aşağıdaki çerçeveyi kaldırmak için eksi işaretini(-) kullanın:

      • GoogleMapsBase (Yalnızca 9.0.0'dan önceki sürümlerden yapılan yükseltmeler için)
      • GoogleMapsCore (Yalnızca 9.0.0'dan önceki sürümlerden yapılan yükseltmeler için)
      • GoogleMapsM4B (Yalnızca 9.0.0'dan önceki sürümlerden yapılan yükseltmeler için)
    2. Xcode'dan "File > (Dosya) > Paketler > En Son Paket Sürümlerine Güncelleyin".
    3. Yüklemenizi doğrulamak için Project Navigator'ın Paket Bağımlılıkları bölümüne gidin .

    CocoaPods, aşağıdaki adımları uygulayın:

    1. Xcode çalışma alanınızı kapatın. Terminali açın ve aşağıdaki komutu yürütün:
      sudo gem install cocoapods-deintegrate cocoapods-clean 
      pod deintegrate 
      pod cache clean --all
      .
    2. Podfile, Podfile.resolved ve CocoaPods dışında bir şey için kullanmıyorsanız Xcode workspace.

    Yüklü olan tüketici SDK'sını kaldırmak için manuel olarak yüklemek istemiyorsanız aşağıdaki adımları uygulayın:

    1. Xcode proje yapılandırma ayarlarınızdan Frameworks, Kitaplıklar ve Yerleştirilmiş İçerikler. Kaldırmak için eksi işaretini(-) kullanın. şu çerçeveyi kullanabilirsiniz:

      • GoogleRidesharingConsumer.xcframework
    2. Xcode projenizin üst düzey dizininden şunu kaldırın: GoogleRidesharingConsumer paketi.

    CocoaPods

    CocoaPods'u kullanarak Tüketici SDK'sını yapılandırmak için: şu öğeleri gerektirir:

    • CocoaPods aracı: Bu aracı yüklemek için Terminal'i açın ve aşağıdaki komuttan yararlanabilirsiniz.

      sudo gem install cocoapods
      

    Daha fazla bilgi için CocoaPods rehberini inceleyin. bolca fırsat sunuyor.

    1. Tüketici SDK'sı için Podfile oluşturun ve bunu kullanın yüklemeniz gerekir. İlk olarak, Proje dizininizde Podfile. Bu dosya, projenizin ve bildirmeyi konuştuk. Ardından Podfile'ı düzenleyin ve bağımlılıklarınızı ekleyin. İşte bağımlılıkları içeren bir örnek:

        source "https://github.com/CocoaPods/Specs.git"
      
        target 'YOUR_APPLICATION_TARGET_NAME_HERE' do
          pod 'GoogleRidesharingConsumer'
        end
      
    2. Podfile'ı kaydedin. Bir terminal penceresi açın ve şunu içeren dizine gidin: Podfile:

      cd <path-to-project>
      
    3. Kapsül yükleme komutunu çalıştırın. Bu işlem, ve sahip oldukları bağımlılıkları gösterir.

      pod install
      
    4. Xcode'u kapatın ve ardından projenizin .xcworkspace dosyasını açın (çift tıklayın) dosyasını seçin. Projeyi daha sonra açmak için .xcworkspace uzantısını kullanın dosyası olarak kaydedebilirsiniz.

    Manuel yükleme

    XCFramework, Tüketici SDK'sı. Bu paketi birden fazla platformlar (M1 yonga seti kullanan makineler dahil). Bu kılavuzda, öğesini içeren XCFramework'ü manuel olarak tüketici SDK'sı ekleyin ve derleme ayarları hakkında daha fazla bilgi edinin.

    SDK ikili programını ve kaynaklarını indirin:

    1. XCFramework ve kaynaklara erişmek için sıkıştırılmış dosyaları açın.

    2. Xcode'u başlatın ve mevcut bir projeyi açın veya yeni bir proje oluşturun belirler. iOS'te yeniyseniz yeni bir proje oluşturun ve iOS'i seçin Uygulama şablonu.

    3. Proje grubunuz yoksa bir Çerçeveler grubu oluşturun zaten.

    4. Tüketici SDK'sını yüklemek için GoogleRidesharingConsumer.xcframework dosyasını projenizde Çerçeveler, Kitaplıklar ve Yerleştirilmiş İçerikler bölümüne sürükleyin. İstendiğinde, gerekirse Öğeleri kopyala'yı seçin.

    5. İndirilen GoogleRidesharingConsumer.bundle dosyasını Xcode projenizin en üst düzey dizinine sürükleyin. İstendiğinde Copy items if needed cihazını seçin.

    6. Project Navigator'dan projenizi seçin ve hedefi belirleyebilirsiniz.

    7. Derleme Aşamaları sekmesini açın ve İkili Program'ı Kitaplıklarla Bağla bölümünde mevcut değilse aşağıdaki çerçeveleri ve kitaplıkları kullanın:

      • 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
    8. Belirli bir hedef yerine projenizi seçin ve Derleme Ayarlar sekmesi. Diğer Bağlayıcı İşaretleri bölümünde şunun için -ObjC ekleyin: hata ayıklamak ve yayınlamaktır. Bu ayarlar görünmüyorsa filtreleyerek Temel'i Tümü olarak değiştirin.

    Apple Gizlilik Manifest dosyasını inceleyin

    Apple, App Store'daki uygulamalar için uygulama gizlilik ayrıntılarını zorunlu kılar. Güncellemeler ve daha fazla bilgi için Apple App Store Gizlilik Ayrıntıları sayfasını ziyaret edin.

    Apple Gizlilik Manifest dosyası, SDK'nın kaynak paketinde yer almaktadır. Gizlilik Manifest Dosyasının dahil edildiğini doğrulamak ve içeriğini incelemek için uygulamanızın arşivini oluşturup arşivden bir gizlilik raporu oluşturun.

    Uygulama entegrasyonu

    Kimlik doğrulama jetonu sağlayın

    Tüketici uygulamanız Fleet Engine'den seyahat güncellemeleri istediğinde geçerli erişim jetonları içermelidir. Bu istekleri yetkilendirmek ve kimliklerini doğrulamak için Tüketici SDK'sı GMTCAuthorization protokolü. Nesne, gerekli erişim jetonu.

    Uygulama geliştirici olarak jetonların nasıl oluşturulacağını siz seçersiniz. Uygulamanız şunları yapmasına imkan tanımalıdır:

    • Bir HTTPS sunucusundan JSON biçiminde erişim jetonu alın.
    • Jetonu ayrıştırıp önbelleğe alın.
    • Jetonu süresi dolduğunda yenileyin.

    Fleet Engine sunucusunun beklediği jetonlarla ilgili ayrıntılar için JSON Web Token (JWT) yetkilendirme başlıklı makaleyi inceleyin.

    Sağlayıcı kimliği, Google Cloud proje kimliği ile aynıdır. Daha fazla bilgi için Filo'yu Kullanmaya Başlama Arama Motoru.

    Aşağıdaki örnekte bir erişim jetonu sağlayıcı uygulanmaktadır:

    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
    

    Uygulama başlatma

    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
    

    Harita görünümü entegrasyonu

    Harita görünümünü başlatma

    Aşağıdaki örnekte GMTCMapView ürününün nasıl başlatılacağı gösterilmektedir.

    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] initWithFrame:CGRectZero];
      self.mapView.settings.myLocationButton = YES;
      self.mapView.delegate = self;
      ...
    }
    
    ...
    
    @end
    

    Harita görünümü etkinliklerini işleme

    Aşağıdaki örnekte, müşteri durumunu yönetmek için bir yetki verilmiş kullanıcının nasıl uygulanacağı gösterilmektedir etkinlikler.

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

    Yolculuk paylaşımı

    Görünüm yüklendiğinde yeni bir gezi başlat

    Aşağıdaki örnekte, görünüm yüklemeleri. Teslim alma ve teslim alma konumları gibi tüm kullanıcı girişlerini toplayabilirsiniz ViewController veri tabanından ve ardından, başlangıç olarak yeni bir ViewController doğrudan yolculuk paylaşımı.

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

    Etkin geziyi iptal et

    Aşağıdaki örnekte mevcut aktif seyahatin nasıl sıfırlanacağı gösterilmektedir.

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

    Gezi güncellemelerini dinleyin

    Aşağıdaki örnekte, tripModel geri çağırmasının nasıl kaydedileceği gösterilmektedir.

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

    Aşağıdaki örnekte, tripModel kaydının nasıl iptal edileceği gösterilmektedir geri arama.

    Swift

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

    Objective-C

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

    Aşağıdaki örnekte, GMTCTripModelSubscriber öğesinin nasıl uygulanacağı gösterilmektedir protokolü kullanabilir.

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

    Hata işleme

    tripModel'e abone olduysanız ve bir hata oluşursa delege yöntemini uygulayarak tripModel tripModel(_:didFailUpdateTripWithError:) Fleet Engine, hatayı oluşturdu mesajı gösterilir. Ayrıntı hatası için mesaj tanımı ve tüm hata kodları; Google Cloud Hataları dokümanlarına göz atın.

    Özellikle, seyahat izleme için geçerli bir kimlik doğrulama işlemi yapılmasını gerektirir. jeton. Geçerli bir kimlik doğrulama işlemi yoksa 401 UNAUTHENTICATED yükseltilir kimlik bilgileri (ör.jetonun süresi dolmuşsa) 403 PERMISSION_DENIED, arayanın belirli bir API'yi çağırma izni yok (örneğin, tüketici sürümü olan kullanıcı rolü, updateTrip'i çağırmaya çalışıyor) veya istekte geçerli bir tool_id/trip_id yok JWT jetonunda.

    Daha fazla bilgi için bkz. Tüketici SDK'sı Hatası Kullanım.

    Kullanıcı Arayüzü Özelleştirme

    Özel çoklu çizgi kullanıcı arayüzü seçeneklerini alma ve ayarlama

    Aşağıdaki örnekte, çoklu çizgiler için özel kullanıcı arayüzü seçeneklerinin nasıl ayarlanacağı gösterilmektedir.

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

    Özel işaretçi kullanıcı arayüzü seçeneklerini alma ve ayarlama

    Aşağıdaki örnekte, işaretçiler için özel kullanıcı arayüzü seçeneklerinin nasıl ayarlanacağı gösterilmektedir.

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

    Kamera yakınlaştırma ayarını değiştirin

    Konumum düğme : iOS için Haritalar SDK'sında bulunan uygulama, kamerayı cihaz konumuna göre ortalar.

    Etkin bir yolculuk paylaşımı oturumu varsa kamerayı ortalayarak cihazın konumuna odaklanmak yerine yolculuğuna odaklanılmasını sağlayın.

    Tüketici SDK'sı, kullanıcıları hedefleyen varsayılan olarak etkindir. Kamera, yolculuk paylaşımı rotasına odaklanmak için görüntüyü yakınlaştırır ve seyahat edeceğim bir sonraki ara noktayı gösterin.

    AutoCamera

    Kamera davranışı üzerinde daha fazla kontrole ihtiyacınız varsa bu özelliği devre dışı bırakabilir veya etkinleştirebilirsiniz otomatik kamera özelliğini isAllowCameraAutoUpdate

    Daha fazla kamera özelleştirmesi için iOS için Haritalar SDK'sı kamera ile kontrol edin.