بدء استخدام حزمة تطوير البرامج (SDK) للمستهلكين لنظام التشغيل iOS

يمكنك استخدام حزمة تطوير البرامج (SDK) للمستهلكين لإنشاء وتشغيل تطبيق أساسي للمستهلك متكامل مع خدمات الواجهة الخلفية لحلول الرحلات عند الطلب والتسليمات. يمكنك إنشاء تطبيق "رحلة طلبك" و"تقدم الطلب" الذي يمكنه عرض رحلة نشطة والاستجابة لتعديلات الرحلات ومعالجة أخطاء الرحلات.

ونظرًا إلى أنّ حزمة "حزمة SDK الخاصة بالمستهلك" تتضمّن بنية نموذجية، يمكنك استخدام أجزاء واجهة برمجة التطبيقات التي تريد استخدامها لتطبيق معيّن ودمجها مع واجهات برمجة التطبيقات الخاصة بك وخدمات الخلفية التي يوفّرها FleetEngine وواجهات برمجة التطبيقات الإضافية في "منصة خرائط 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. من نافذة اختيار منتجات الحزمة، تأكَّد من إضافة GoogleRidesharingConsumer إلى هدف main المحدَّد. بعد اكتمال عملية النقل، انقر على "إضافة حزمة".
    5. للتحقّق من عملية التثبيت، انتقِل إلى جزء General في استهدافك. من المفترَض أن تظهر الحِزَم المثبَّتة في أُطر العمل والمكتبات والمحتوى المضمَّن. يمكنك أيضًا الاطّلاع على قسم "تبعيات الحِزم" ضمن Project Navigator (أداة التنقّل في المشروع) للتحقّق من الحزمة وإصدارها.

    لتعديل package لمشروع حالي، اتّبِع الخطوات التالية:

    1. في حال الترقية من إصدار أقدم من 9.0.0، عليك إزالة الاعتماديات التالية: GoogleMapsBase وGoogleMapsCore وGoogleMapsM4B بعد الترقية. يجب عدم إزالة تبعية GoogleMaps. لمعرفة مزيد من المعلومات، يمكنك الاطّلاع على ملاحظات الإصدار 9.0.0.

      من إعدادات ضبط مشروع Xcode، ابحث عن الإطارات والمكتبات والمحتوى المضمَّن. استخدِم علامة الطرح(-) لإزالة إطار العمل التالي:

      • GoogleMapsBase (للترقيات من الإصدارات السابقة على 9.0.0 فقط)
      • GoogleMapsCore (للترقيات من الإصدارات السابقة على 9.0.0 فقط)
      • GoogleMapsM4B (للترقيات من الإصدارات السابقة على 9.0.0 فقط)
    2. من Xcode، انتقِل إلى "ملف" > "الحِزم" > "تحديث إلى أحدث إصدارات الحزمة".
    3. للتحقّق من عملية التثبيت، انتقِل إلى القسم تبعيات الحزمة في 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، ابحث عن الإطارات والمكتبات والمحتوى المضمَّن. استخدم علامة الطرح(-) لإزالة إطار العمل التالي:

      • GoogleRidesharingConsumer.xcframework
    2. من دليل المستوى الأعلى لمشروع Xcode، أزِل الحزمة GoogleRidesharingConsumer.

    CocoaPods

    لإعداد حزمة تطوير البرامج (SDK) للمستهلكين باستخدام CocoaPods، يجب توفّر العناصر التالية:

    • أداة CocoaPods: لتثبيت هذه الأداة، افتح المحطة الطرفية وشغِّل الأمر التالي.

      sudo gem install cocoapods
      

    يمكنك مراجعة دليل بدء استخدام CocoaPods للاطّلاع على مزيد من التفاصيل.

    1. قم بإنشاء Podfile لـ Consumer SDK واستخدمه لتثبيت واجهة برمجة التطبيقات وتبعياتها. أولاً، قم بإنشاء ملف يسمى 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 install. سيؤدي ذلك إلى تثبيت واجهات برمجة التطبيقات المحددة في Podfile، إلى جانب أي ملحقات قد تكون لديهم.

      pod install
      
    4. أغلق Xcode ثم افتح ملف xcworkspace لمشروعك (بالنقر المزدوج) لتشغيل Xcode. لفتح المشروع لاحقًا، استخدم ملف xcworkspace.

    التثبيت اليدوي

    XCFramework عبارة عن حزمة ثنائية تستخدمها لتثبيت حزمة SDK للمستهلك. يمكنك استخدام هذه الحزمة على أنظمة أساسية متعددة، بما في ذلك الأجهزة التي تستخدم شريحة M1. يوضح هذا الدليل كيفية إضافة XCFramework الذي يحتوي على Consumer SDK إلى مشروعك يدويًا إلى مشروعك وضبط إعدادات الإصدار في Xcode.

    تنزيل البرنامج الثنائي لحزمة SDK والموارد:

    1. فك ضغط الملفات المضغوطة للوصول إلى XCFramework والموارد.

    2. ابدأ Xcode وافتح مشروعًا حاليًا أو أنشئ مشروعًا جديدًا. إذا كنت مبتدئًا في استخدام iOS، أنشئ مشروعًا جديدًا واختَر نموذج تطبيق iOS.

    3. قم بإنشاء مجموعة أطر عمل ضمن مجموعة المشروعات إذا لم تكن موجودة بالفعل.

    4. لتثبيت "حزمة SDK للمستهلك"، اسحب ملف "GoogleRidesharingConsumer.xcframework" إلى مشروعك ضمن "أعمال الإطارات" و"المكتبات" و"المحتوى المضمَّن. اختَر نسخ العناصر إذا لزم الأمر عندما يُطلب منك ذلك.

    5. اسحب ملف GoogleRidesharingConsumer.bundle الذي تم تنزيله إلى دليل المستوى الأعلى في مشروع Xcode. اختَر "Copy items if needed" عندما يُطلب منك ذلك.

    6. اختَر مشروعك من Project Navigator واختر هدف تطبيقك.

    7. افتح علامة التبويب "مراحل الإنشاء"، وفي "Link Binary with Libraries" (رابط Binary مع المكتبات)، أضف أطر العمل والمكتبات التالية إذا لم تكن موجودة بالفعل:

      • 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. اختر مشروعك بدلاً من هدف محدد، وافتح علامة التبويب إعدادات إنشاء. في القسم علامات الرابط الأخرى، أضِف -ObjC لكل من تصحيح الأخطاء والإصدار. إذا لم تكن هذه الإعدادات مرئية، غيِّر الفلتر في شريط "إعدادات الإصدار" من أساسي إلى الكل.

    إضافة ملف بيان الخصوصية في 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. الكائن هو المسؤول عن تقديم رمز الدخول المطلوب.

    بصفتك مطوّر التطبيق، أنت تختار كيفية إنشاء الرموز المميّزة. وينبغي أن يوفر التنفيذ الخاص بك القدرة على القيام بما يلي:

    • استرجاع رمز دخول، ربما بتنسيق JSON، من خادم HTTPS.
    • تحليل الرمز المميّز وتخزينه مؤقتًا
    • أعِد تحميل الرمز المميّز عند انتهاء صلاحيته.

    لمعرفة تفاصيل الرموز المميّزة التي يتوقعها خادم Fleet Engine، يُرجى الاطّلاع على إنشاء رمز JSON المميّز للويب (JWT) للتفويض.

    رقم تعريف مقدّم الخدمة هو نفسه رقم تعريف مشروع Google Cloud. لمزيد من المعلومات، يُرجى الاطّلاع على بدء استخدام FleetEngine.

    يقدم المثال التالي موفّرًا لرمز الدخول:

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

    يوضّح المثال التالي كيفية إلغاء تسجيل طلب معاودة الاتصال tripModel.

    Swift

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

    Objective-C

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

    يوضّح المثال التالي كيفية تنفيذ بروتوكول GMTCTripModelSubscriber للتعامل مع طلبات معاودة الاتصال عند تعديل حالة الرحلة.

    Swift

    /*
    
        *   MapViewController.swift
     */
    func tripModel(_: GMTCTripModel, didUpdate trip: GMTSTrip?, updatedPropertyFields: GMTSTripPropertyFields) {
      // Update the UI with the new `trip` data.
      self.updateUI(with: trip)
    }
    
    func tripModel(_: GMTCTripModel, didUpdate tripStatus: GMTSTripStatus) {
      // Handle trip status did change.
    }
    
    func tripModel(_: GMTCTripModel, didUpdateActiveRouteRemainingDistance activeRouteRemainingDistance: Int32) {
      // Handle remaining distance of active route did update.
    }
    
    func tripModel(_: GMTCTripModel, didUpdateActiveRoute activeRoute: [GMTSLatLng]?) {
      // Handle trip active route did update.
    }
    
    func tripModel(_: GMTCTripModel, didUpdate vehicleLocation: GMTSVehicleLocation?) {
      // Handle vehicle location did update.
    }
    
    func tripModel(_: GMTCTripModel, didUpdatePickupLocation pickupLocation: GMTSTerminalLocation?) {
      // Handle pickup location did update.
    }
    
    func tripModel(_: GMTCTripModel, didUpdateDropoffLocation dropoffLocation: GMTSTerminalLocation?) {
      // Handle drop off location did update.
    }
    
    func tripModel(_: GMTCTripModel, didUpdatePickupETA pickupETA: TimeInterval) {
      // Handle the pickup ETA did update.
    }
    
    func tripModel(_: GMTCTripModel, didUpdateDropoffETA dropoffETA: TimeInterval) {
      // Handle the drop off ETA did update.
    }
    
    func tripModel(_: GMTCTripModel, didUpdateRemaining remainingWaypoints: [GMTSTripWaypoint]?) {
      // Handle updates to the pickup, dropoff or intermediate destinations of the trip.
    }
    
    func tripModel(_: GMTCTripModel, didFailUpdateTripWithError error: Error?) {
      // Handle the error.
    }
    
    func tripModel(_: GMTCTripModel, didUpdateIntermediateDestinations intermediateDestinations: [GMTSTerminalLocation]?) {
      // Handle the intermediate destinations being updated.
    }
    
    func tripModel(_: GMTCTripModel, didUpdateActiveRouteTraffic activeRouteTraffic: GMTSTrafficData?) {
      // Handle trip active route traffic being updated.
    }
    

    Objective-C

    /*
    
        *   MapViewController.m
     */
    #pragma mark - GMTCTripModelSubscriber implementation
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
                didUpdateTrip:(nullable GMTSTrip *)trip
        updatedPropertyFields:(enum GMTSTripPropertyFields)updatedPropertyFields {
      // Update the UI with the new `trip` data.
      [self updateUIWithTrip:trip];
      ...
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel didUpdateTripStatus:(enum GMTSTripStatus)tripStatus {
      // Handle trip status did change.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
        didUpdateActiveRouteRemainingDistance:(int32_t)activeRouteRemainingDistance {
       // Handle remaining distance of active route did update.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
        didUpdateActiveRoute:(nullable NSArray<GMTSLatLng *> *)activeRoute {
      // Handle trip active route did update.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
        didUpdateVehicleLocation:(nullable GMTSVehicleLocation *)vehicleLocation {
      // Handle vehicle location did update.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
        didUpdatePickupLocation:(nullable GMTSTerminalLocation *)pickupLocation {
      // Handle pickup location did update.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
        didUpdateDropoffLocation:(nullable GMTSTerminalLocation *)dropoffLocation {
      // Handle drop off location did update.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel didUpdatePickupETA:(NSTimeInterval)pickupETA {
      // Handle the pickup ETA did update.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
        didUpdateRemainingWaypoints:(nullable NSArray<GMTSTripWaypoint *> *)remainingWaypoints {
      // Handle updates to the pickup, dropoff or intermediate destinations of the trip.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel didUpdateDropoffETA:(NSTimeInterval)dropoffETA {
      // Handle the drop off ETA did update.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel didFailUpdateTripWithError:(nullable NSError *)error {
      // Handle the error.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
        didUpdateIntermediateDestinations:
            (nullable NSArray<GMTSTerminalLocation *> *)intermediateDestinations {
      // Handle the intermediate destinations being updated.
    }
    
    -   (void)tripModel:(GMTCTripModel *)tripModel
        didUpdateActiveRouteTraffic:(nullable GMTSTrafficData *)activeRouteTraffic {
      // Handle trip active route traffic being updated.
    }
    

    خطأ أثناء المعالجة

    إذا اشتركت في tripModel وحدث خطأ، يمكنك الحصول على استدعاء tripModel من خلال تنفيذ طريقة التفويض tripModel(_:didFailUpdateTripWithError:). أنشأ Fleet Engine رسالة الخطأ التي تتبع معيار الخطأ في Google Cloud. للحصول على تعريف تفصيلي لرسالة الخطأ وجميع رموز الأخطاء، يُرجى الرجوع إلى مستندات أخطاء Google Cloud.

    ولمراقبة الرحلات على وجه التحديد، يتطلّب ذلك توفير رمز مصادقة صالح. سيتم رفع 401 UNAUTHENTICATED في حال عدم توفّر بيانات اعتماد صالحة للمصادقة، كانتهاء صلاحية الرمز المميّز.403 PERMISSION_DENIED سيتم تقديم الطلب إذا لم يكن لدى المتصل إذن للاتصال بواجهة برمجة تطبيقات معيّنة (على سبيل المثال، يحاول المستخدم الذي لديه دور المستهلك استدعاء updateTrip) أو لا يتضمن الطلب رمزًا مميّزًا صالحًا للمركبة في 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];
    }
    

    جارٍ ضبط التكبير أو التصغير في الكاميرا

    يعمل زر "موقعي" في حزمة SDK لخرائط Google لنظام التشغيل iOS على تركيز الكاميرا على موقع الجهاز.

    إذا كانت هناك جلسة "مشاركة الرحلة" نشطة، يمكنك توسيط الكاميرا للتركيز على الرحلة بدلاً من التركيز على الموقع الجغرافي للجهاز فقط.

    توفر حزمة تطوير البرامج (SDK) للمستهلك ميزة كاميرا تلقائية يتم تفعيلها تلقائيًا. يتم تكبير الكاميرا للتركيز على مسار مشاركة الرحلة ونقطة الطريق التالية للرحلة.

    AutoCamera

    إذا أردت التحكّم بشكل أكبر في سلوك الكاميرا، يمكنك إيقاف ميزة "الكاميرا التلقائية" أو تفعيلها باستخدام سمة isAllowCameraAutoUpdate.

    للحصول على المزيد من عمليات تخصيص الكاميرا، يُرجى الاطّلاع على حزمة تطوير البرامج بالاستناد إلى بيانات "خرائط Google" لنظام التشغيل iOS من أجل نقل الكاميرا.