תחילת העבודה עם SDK SDK ל-iOS

תוכלו להשתמש ב-SDK לצרכן כדי ליצור ולהפעיל אפליקציית צרכן בסיסית שמשולבת בשירותים לקצה העורפי של 'נסיעות ומשלוחים על פי דרישה'. אתם יכולים ליצור אפליקציה של 'נסיעה פעילה' ושל 'התקדמות ההזמנה' שיכולה להציג נסיעה פעילה, להגיב לעדכוני נסיעה ולטפל בשגיאות בנסיעה.

מכיוון שלצרכן ה-SDK יש ארכיטקטורה מודולרית, תוכלו להשתמש בחלקי ה-API שבהם תרצו להשתמש באפליקציה הספציפית שלכם, ולשלב אותם בממשקי API משלכם, בשירותים לקצה העורפי שמסופקים על ידי Fleet Engine, וממשקי API נוספים של הפלטפורמה של מפות Google.

דרישות מערכת מינימליות

  • במכשיר הנייד צריכה לפעול מערכת iOS בגרסה 14 ואילך.
  • Xcode מגרסה 15 ואילך.
  • הגדרות אישיות של פרויקט

    מנהל חבילות SWIFT

    ניתן להתקין את ה-SDK לצרכנים דרך Swift Package Manager. כדי להוסיף את ה-SDK, צריך לוודא שהסרתם את כל יחסי התלות הקיימים של ה-SDK לצרכנים.

    כדי להוסיף את ה-SDK לפרויקט חדש או קיים:

    1. פותחים את ה-Xcode project או workspace ועוברים אל 'קובץ' > 'הוספת יחסי תלות של חבילה'.
    2. מזינים את הכתובת https://github.com/googlemaps/ios-consumer-sdk בתור כתובת ה-URL, מקישים על Enter כדי למשוך את החבילה ולוחצים על 'הוספת חבילה'.
    3. כדי להתקין version ספציפי, צריך להגדיר את השדה כלל תלות לאחת מהאפשרויות שמבוססות על גרסה. בפרויקטים חדשים, מומלץ לציין את הגרסה האחרונה ולהשתמש באפשרות 'גרסה מדויקת'. בסיום, לוחצים על 'הוספת חבילה'.
    4. בחלון Choose Package Products, מוודאים שהערך של GoogleRidesharingConsumer יתווסף ליעד main שציינתם. בסיום, לוחצים על 'הוספת חבילה'.
    5. כדי לבדוק את ההתקנה, צריך לעבור לחלונית General של היעד. ב-Frameworks, ספריות ותוכן מוטמע אתם אמורים לראות את החבילות המותקנות. אפשר גם לעיין בקטע 'יחסי תלות של חבילה' בדף 'Project Navigator' כדי לאמת את החבילה ואת הגרסה שלה.

    כדי לעדכן את package בפרויקט קיים:

    1. אם משדרגים מגרסה קודמת מ-9.0.0, צריך להסיר את יחסי התלות הבאים: GoogleMapsBase, GoogleMapsCore ו-GoogleMapsM4B לאחר השדרוג. אין להסיר את התלות של GoogleMaps. למידע נוסף, ראו את נתוני הגרסה של גרסה 9.0.0.

      בהגדרות האישיות של פרויקט Xcode, מחפשים את Frameworks, ספריות ותוכן מוטמע. משתמשים בסימן המינוס(-) כדי להסיר את המסגרת הבאה:

      • GoogleMapsBase (רק לשדרוגים מגרסאות מוקדמות יותר מ-9.0.0)
      • GoogleMapsCore (רק לשדרוגים מגרסאות מוקדמות יותר מ-9.0.0)
      • GoogleMapsM4B (רק לשדרוגים מגרסאות מוקדמות יותר מ-9.0.0)
    2. מ-Xcode, עוברים אל 'קובץ' > 'חבילות' > 'עדכון לגרסאות האחרונות של החבילה'.
    3. כדי לאמת את ההתקנה, עוברים לקטע Package Dependencies של Project Navigator כדי לאמת את החבילה ואת הגרסה שלה.

    כדי להסיר יחסי תלות קיימים של SDK לצרכנים שנוספו באמצעות CocoaPods, צריך לבצע את השלבים הבאים:

    1. סוגרים את סביבת העבודה של Xcode. פותחים את הטרמינל ומריצים את הפקודה הבאה:
      sudo gem install cocoapods-deintegrate cocoapods-clean 
      pod deintegrate 
      pod cache clean --all
    2. מסירים את Podfile, Podfile.resolved ואת ה-Xcode workspace אם אתם לא משתמשים בהם לכל מטרה אחרת מלבד CocoaPods.

    כדי להסיר את ערכת ה-SDK הקיימת לצרכן שהותקנה באופן ידני, מבצעים את השלבים הבאים:

    1. בהגדרות של פרויקט Xcode, מחפשים את Frameworks, ספריות ותוכן מוטמע. משתמשים בסימן המינוס(-) כדי להסיר את המסגרת הבאה:

      • GoogleRidesharingConsumer.xcframework
    2. מהספרייה ברמה העליונה של פרויקט Xcode, מסירים את החבילה GoogleRidesharingConsumer.

    CocoaPods

    כדי להגדיר את ה-SDK לצרכנים באמצעות CocoaPods, צריך את הפריטים הבאים:

    • הכלי CocoaPods: כדי להתקין את הכלי, פותחים את הטרמינל ומריצים את הפקודה הבאה.

      sudo gem install cocoapods
      

    לפרטים נוספים, ראו מדריך לתחילת העבודה של CocoaPods.

    1. יוצרים קובץ Podfile ל-SDK לצרכנים ומשתמשים בו כדי להתקין את ה-API ואת יחסי התלות שלו. קודם כול, יוצרים קובץ בשם Podfile בספריית הפרויקט. הקובץ הזה מגדיר את יחסי התלות של הפרויקט. לאחר מכן עורכים את ה-Podfile ומוסיפים את יחסי התלות. לפניכם דוגמה שכוללת את יחסי התלות:

        source "https://github.com/CocoaPods/Specs.git"
      
        target 'YOUR_APPLICATION_TARGET_NAME_HERE' do
          pod 'GoogleRidesharingConsumer'
        end
      
    2. שומרים את ה-Podfile. פותחים טרמינל ועוברים לספרייה שמכילה את ה-Podfile:

      cd <path-to-project>
      
    3. מריצים את פקודת ההתקנה של pod. הפעולה הזו תתקין את ממשקי ה-API שצוינו ב-Podfile, יחד עם כל יחסי התלות שיש להם.

      pod install
      
    4. סוגרים את Xcode ואז פותחים (לחיצה כפולה) את קובץ ה- .xcworkspace של הפרויקט כדי להפעיל את Xcode. כדי לפתוח את הפרויקט מאוחר יותר, משתמשים בקובץ .xcworkspace

    התקנה ידנית

    XCFramework היא חבילה בינארית שבה משתמשים כדי להתקין את ה-SDK לצרכנים. אפשר להשתמש בחבילה הזו בכמה פלטפורמות, כולל מכונות שמשתמשות בערכת השבבים M1. במדריך הזה מוסבר איך להוסיף באופן ידני את ה-XCFramework שמכיל את Consumer SDK לפרויקט שלכם, ולקבוע את הגדרות ה-build ב-Xcode.

    מורידים את הקובץ הבינארי ומשאבים של ה-SDK:

    1. פורקים את קובצי ה-ZIP כדי לגשת ל-XCFramework ולמשאבים.

    2. מתחילים את Xcode ופותחים פרויקט קיים, או יוצרים פרויקט חדש. אם זו הפעם הראשונה שאתם משתמשים ב-iOS, אתם צריכים ליצור פרויקט חדש ולבחור את תבנית האפליקציה ל-iOS.

    3. אם עדיין לא קיימת קבוצה, יוצרים קבוצת Frameworks תחת קבוצת הפרויקט.

    4. כדי להתקין את Consumer SDK, גוררים את הקובץ GoogleRidesharingConsumer.xcframework אל הפרויקט בקטע Frameworks, ספריות ותוכן מוטמע. כשתתבקשו, בחרו באפשרות 'העתקת פריטים', אם יש צורך.

    5. גוררים את הקובץ GoogleRidesharingConsumer.bundle שהורדתם לספרייה ברמה העליונה של פרויקט Xcode. כשמופיעה בקשה, בוחרים באפשרות Copy items if needed.

    6. בוחרים את הפרויקט מ-Project Navigator ובוחרים את יעד האפליקציה.

    7. פותחים את הכרטיסייה Build Phases (שלבי פיתוח), וב-Link Binary with Libraries, מוסיפים את ה-frameworks והספריות הבאות אם הן עדיין לא קיימות:

      • 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. בוחרים את הפרויקט ולא יעד ספציפי ופותחים את הכרטיסייה Build Settings. בקטע Other Linker Banners (סימון לקישור אחר), מוסיפים את -ObjC גם לניפוי באגים וגם לגרסה. אם ההגדרות האלה לא מוצגות, משנים את המסנן בסרגל ההגדרות של Build מ-Basic ל-All.

    הוספת קובץ מניפסט הפרטיות של Apple

    Apple דורשת פרטים לגבי הפרטיות של אפליקציות ב-App Store. עדכונים ומידע נוסף זמינים בדף פרטי הפרטיות של Apple App Store.

    1. מורידים את חבילת מניפסט הפרטיות לערכת ה-SDK לצרכנים ל-iOS: GoogleRidesharingConsumerPrivacy.
    2. מחלצים את הקובץ כדי לגשת אל GoogleRidesharingConsumerPrivacy.bundle.
    3. מוסיפים את GoogleRidesharingConsumerPrivacy.bundle לכלי הניווט בפרויקט Xcode באמצעות אחת מהשיטות האלה. מוודאים שהתיבה 'הוספה ליעדים' מסומנת ביעד של האפליקציה. לאחר ההוספה, הקובץ PrivacyInfo יופיע בכלי הניווט בפרויקט ותוכלו לבדוק את הערכים.
    4. צילום מסך של פרטי הפרטיות של Xcode
    5. כדי לוודא שמניפסט הפרטיות נוסף, צריך ליצור ארכיון של האפליקציה וליצור דוח פרטיות מהארכיון.

    שילוב אפליקציה

    מסירת אסימון אימות

    כשהאפליקציה לצרכן מבקשת עדכוני נסיעה מ-Fleet Engine, הבקשות חייבות לכלול אסימוני גישה תקפים. כדי לאשר ולאמת את הבקשות האלה, ה-SDK לצרכנים קורא לאובייקט שתואם לפרוטוקול GMTCAuthorization. האובייקט אחראי לספק את אסימון הגישה הנדרש.

    כמפתחי האפליקציה, אתם בוחרים איך האסימונים נוצרים. ההטמעה צריכה לאפשר לכם לבצע את הפעולות הבאות:

    • מאחזרים אסימון גישה משרת HTTPS, כנראה בפורמט JSON.
    • ניתוח האסימון ושמירה שלו במטמון.
    • צריך לרענן את האסימון כשהתוקף שלו יפוג.

    לפרטים על האסימונים הנדרשים מהשרת Fleet Engine, קראו את המאמר יצירת אסימון אינטרנט מסוג JSON (JWT) לצורך הרשאה.

    מזהה הספק זהה למזהה הפרויקט ב-Google Cloud. למידע נוסף, ראו תחילת העבודה עם 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] initWithFrame:CGRectZero];
      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] 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];
      ...
    }
    

    הדוגמה הבאה מראה איך לבטל את הרישום של הקריאה החוזרת (callback) של 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.
    }
    

    טיפול בשגיאות

    אם נרשמתם ל-travelModel ומופיעה שגיאה, אפשר לקבל את הקריאה החוזרת שלtripModel על ידי הטמעת השיטה להענקת גישה tripModel(_:didFailUpdateTripWithError:). Fleet Engine יצר את הודעת השגיאה בהתאם לתקן Google Cloud Error. להסבר מפורט על ההגדרה של הודעת השגיאה ועל כל קודי השגיאה, עיינו במסמכי העזרה של Google Cloud Error.

    באופן ספציפי, כדי לעקוב אחרי נסיעות צריך לספק אסימון אימות תקף. תתבצע העלאה של 401 UNAUTHENTICATED אם אין פרטי כניסה תקפים לאימות, למשל פג תוקפו של האסימון.403 PERMISSION_DENIED תתבצע העלאה אם למבצע הקריאה אין הרשאה לקרוא לממשק API ספציפי (לדוגמה, משתמש עם תפקיד צרכן מנסה לקרוא ל-updateTrip) או אם אין לבקשה פרטי כניסה תקפים של רכב_id/trip_id באסימון JWT.

    מידע נוסף זמין במאמר טיפול בשגיאות ב-SDK לצרכנים.

    התאמה אישית של ממשק המשתמש

    קבלה והגדרה של אפשרויות מותאמות אישית לממשק משתמש של קווים פוליגוניים

    הדוגמה הבאה מראה איך להגדיר אפשרויות מותאמות אישית של ממשק משתמש לקווים פוליגוניים.

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

    קבלה והגדרה של אפשרויות בממשק המשתמש של סמנים בהתאמה אישית

    בדוגמה הבאה אפשר לראות איך להגדיר אפשרויות של ממשק משתמש בהתאמה אישית לסמנים.

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

    כוונון המרחק מהתצוגה של המצלמה

    הלחצן My Location (המיקום שלי) ב-SDK של מפות Google ל-iOS ממרכז את המצלמה במיקום המכשיר.

    אם יש סשן פעיל של שיתוף מסלול, אפשר למרכז את המצלמה כדי להתמקד בתהליך במקום רק במיקום המכשיר.

    ערכת ה-SDK לצרכן מספקת תכונת מצלמה אוטומטית שמופעלת כברירת מחדל. המצלמה משנה את מרחק התצוגה כדי להתמקד במסלול לשיתוף הנסיעה ובציון הדרך הבא.

    AutoCamera

    אם אתם צריכים יותר שליטה בהתנהגות המצלמה, תוכלו להשבית או להפעיל את התכונה של המצלמה האוטומטית באמצעות המאפיין isAllowCameraAutoUpdate.

    להתאמה אישית נוספת של המצלמה, ראו SDK של מפות Google ל-iOS הזזת המצלמה.