การเริ่มต้นใช้งาน Consumer SDK สําหรับ iOS

คุณสามารถใช้ Consumer SDK เพื่อสร้างและเรียกใช้แอปพื้นฐานสำหรับผู้บริโภคซึ่งผสานรวมกับบริการแบ็กเอนด์ของโซลูชันบริการโดยสารและการนำส่งแบบออนดีมานด์ คุณสามารถสร้างแอปการเดินทางและความคืบหน้าในคำสั่งซื้อที่แสดงการเดินทางที่ดำเนินอยู่ ตอบกลับการอัปเดตการเดินทาง และจัดการข้อผิดพลาดในการเดินทางได้

เนื่องจาก Consumer SDK มีสถาปัตยกรรมแบบแยกส่วน คุณจึงสามารถใช้ส่วนต่างๆ ของ API ที่ต้องการใช้กับแอปหนึ่งๆ และผสานรวมเข้ากับ API ของคุณเอง, บริการแบ็กเอนด์จาก Fleet Engine และ API เพิ่มเติมของ Google Maps Platform

ข้อกำหนดขั้นต่ำของระบบ

  • อุปกรณ์เคลื่อนที่ต้องใช้ iOS 14 ขึ้นไป
  • Xcode เวอร์ชัน 15 ขึ้นไป
  • การกำหนดค่าโปรเจ็กต์

    เครื่องมือจัดการแพ็กเกจ Swift

    ติดตั้ง Consumer SDK ได้ผ่าน Swift Package Manager หากต้องการเพิ่ม SDK โปรดตรวจสอบว่าคุณได้นําทรัพยากร Dependency ของ 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 คุณต้องนำทรัพยากร Dependency ต่อไปนี้ออก: GoogleMapsBase, GoogleMapsCore และ GoogleMapsM4B หลังจากอัปเกรด อย่านำการอ้างอิงสำหรับ GoogleMaps ออก ดูข้อมูลเพิ่มเติมได้ในบันทึกประจำรุ่นของเวอร์ชัน 9.0.0

      จากการตั้งค่าการกำหนดค่าโปรเจ็กต์ Xcode ให้ค้นหา Frameworks, Libraries และเนื้อหาแบบฝัง ใช้เครื่องหมายลบ(-)เพื่อนำเฟรมเวิร์กต่อไปนี้ออก

      • GoogleMapsBase (สำหรับการอัปเกรดจากเวอร์ชันก่อน 9.0.0 เท่านั้น)
      • GoogleMapsCore (สำหรับการอัปเกรดจากเวอร์ชันก่อน 9.0.0 เท่านั้น)
      • GoogleMapsM4B (สำหรับการอัปเกรดจากเวอร์ชันก่อน 9.0.0 เท่านั้น)
    2. จาก Xcode ให้ไปที่ "ไฟล์ > แพ็กเกจ > อัปเดตเป็นเวอร์ชันล่าสุดของแพ็กเกจ"
    3. หากต้องการยืนยันการติดตั้ง ให้ไปที่ส่วนการอ้างอิงแพ็กเกจของ Project Navigator เพื่อตรวจสอบแพ็กเกจและเวอร์ชันของแพ็กเกจ

    หากต้องการนำทรัพยากร Dependency ของ Consumer SDK ที่มีอยู่ออกโดยใช้ CocoaPods ให้ทำตามขั้นตอนต่อไปนี้

    1. ปิดพื้นที่ทำงาน Xcode เปิดเทอร์มินัลและเรียกใช้คำสั่งต่อไปนี้
      sudo gem install cocoapods-deintegrate cocoapods-clean 
      pod deintegrate 
      pod cache clean --all
    2. นำ Podfile, Podfile.resolved และ Xcode workspace ออกหากคุณไม่ได้ใช้ CocoaPods อย่างอื่น

    หากต้องการนำ Consumer SDK ที่มีอยู่ซึ่งติดตั้งด้วยตนเองออก ให้ทำตามขั้นตอนต่อไปนี้

    1. จากการตั้งค่าการกำหนดค่าโปรเจ็กต์ Xcode ให้ค้นหา Frameworks, Library, and Embedded Content ใช้เครื่องหมายลบ(-)เพื่อนำเฟรมเวิร์กต่อไปนี้ออก

      • GoogleRidesharingConsumer.xcframework
    2. นำแพ็กเกจ GoogleRidesharingConsumer ออกจากไดเรกทอรีระดับบนสุดของโปรเจ็กต์ Xcode

    CocoaPods

    หากต้องการกำหนดค่า Consumer SDK โดยใช้ CocoaPods คุณต้องมีรายการต่อไปนี้

    • เครื่องมือ CocoaPods: หากต้องการติดตั้งเครื่องมือนี้ ให้เปิดเทอร์มินัลแล้วเรียกใช้คำสั่งต่อไปนี้

      sudo gem install cocoapods
      

    ดูรายละเอียดเพิ่มเติมได้ที่คู่มือเริ่มต้นใช้งาน CocoaPods

    1. สร้าง Podfile สำหรับ Consumer SDK และใช้เพื่อติดตั้ง API และทรัพยากร Dependency ก่อนอื่น ให้สร้างไฟล์ชื่อ Podfile ในไดเรกทอรีโปรเจ็กต์ ไฟล์นี้จะระบุการขึ้นต่อกันของโปรเจ็กต์ จากนั้นแก้ไข Podfile และเพิ่มทรัพยากร Dependency ต่อไปนี้คือตัวอย่างการใช้ทรัพยากร Dependency ด้วย

        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. เรียกใช้คำสั่งติดตั้งพ็อด การดำเนินการนี้จะติดตั้ง API ที่ระบุใน Podfile พร้อมกับทรัพยากร Dependency ต่างๆ ที่ API อาจมี

      pod install
      
    4. ปิด Xcode แล้วเปิด (ดับเบิลคลิก) ไฟล์ .xcworkspace ของโปรเจ็กต์เพื่อเปิด Xcode หากต้องการเปิดโปรเจ็กต์ในภายหลัง ให้ใช้ไฟล์ .xcworkspace

    การติดตั้งด้วยตนเอง

    XCFramework เป็นแพ็กเกจไบนารีที่คุณใช้ติดตั้ง Consumer SDK คุณใช้แพ็กเกจนี้ได้ในหลายแพลตฟอร์ม รวมถึงเครื่องที่ใช้ชิปเซ็ต M1 คู่มือนี้แสดงวิธีเพิ่ม XCFramework ที่มี Consumer SDK ลงในโปรเจ็กต์ของคุณด้วยตนเองและกำหนดการตั้งค่าบิลด์ใน Xcode

    ดาวน์โหลดไบนารี SDK และทรัพยากร ดังนี้

    1. แตกไฟล์ ZIP เพื่อเข้าถึง XCFramework และทรัพยากร

    2. เริ่มต้น Xcode และเปิดโปรเจ็กต์ที่มีอยู่หรือสร้างโปรเจ็กต์ใหม่ หากคุณเพิ่งเริ่มใช้ iOS ให้สร้างโปรเจ็กต์ใหม่และเลือกเทมเพลตแอป iOS

    3. สร้างกลุ่มเฟรมเวิร์กภายใต้กลุ่มโปรเจ็กต์หากยังไม่มี

    4. หากต้องการติดตั้ง Consumer SDK ให้ลากไฟล์ GoogleRidesharingConsumer.xcframework ไปไว้ในโปรเจ็กต์ในส่วนเฟรมเวิร์ก ไลบรารี และเนื้อหาที่ฝัง เมื่อมีข้อความแจ้ง ให้เลือกคัดลอกรายการหากจำเป็น

    5. ลาก GoogleRidesharingConsumer.bundle ที่ดาวน์โหลดมาไปยังไดเรกทอรีระดับบนสุดของโปรเจ็กต์ Xcode เมื่อมีข้อความแจ้ง ให้เลือก Copy items if needed

    6. เลือกโปรเจ็กต์จาก Project Navigator แล้วเลือกเป้าหมายของแอปพลิเคชัน

    7. เปิดแท็บระยะของการสร้างและในลิงก์ไบนารีกับไลบรารี ให้เพิ่มเฟรมเวิร์กและไลบรารีต่อไปนี้หากยังไม่ได้มีอยู่

      • 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. เลือกโปรเจ็กต์แทนเป้าหมายที่เฉพาะเจาะจง แล้วเปิดแท็บสร้างการตั้งค่า ในส่วนแฟล็กอื่นๆ ของ Linker ให้เพิ่ม -ObjC สำหรับทั้งการแก้ไขข้อบกพร่องและรุ่น หากไม่เห็นการตั้งค่าเหล่านี้ ให้เปลี่ยนตัวกรองในแถบการตั้งค่าการสร้างจากพื้นฐานเป็นทั้งหมด

    เพิ่มไฟล์ Manifest ด้านความเป็นส่วนตัวของ Apple

    Apple ต้องการรายละเอียดความเป็นส่วนตัวของแอปสำหรับแอปใน App Store ไปที่หน้ารายละเอียดความเป็นส่วนตัวของ Apple App Store เพื่อดูข้อมูลอัปเดตและข้อมูลเพิ่มเติม

    1. ดาวน์โหลดแพ็กเกจไฟล์ Manifest ด้านความเป็นส่วนตัวสำหรับ Consumer SDK สำหรับ iOS: GoogleRidesharingConsumerPrivacy
    2. แตกไฟล์เพื่อเข้าถึง GoogleRidesharingConsumerPrivacy.bundle
    3. เพิ่ม GoogleRidesharingConsumerPrivacy.bundle ลงในตัวนำทางโปรเจ็กต์ Xcode โดยใช้วิธีใดวิธีหนึ่งเหล่านี้ ตรวจสอบว่าได้เลือกช่อง "เพิ่มในเป้าหมาย" สำหรับเป้าหมายของแอปแล้ว เมื่อเพิ่มแล้ว ไฟล์ PrivacyInfo จะแสดงในตัวนำทางโปรเจ็กต์ และคุณสามารถตรวจสอบค่าได้
    4. ภาพหน้าจอข้อมูลความเป็นส่วนตัวของ Xcode
    5. ยืนยันว่ามีการเพิ่มไฟล์ Manifest ด้านความเป็นส่วนตัวโดยการสร้างที่เก็บถาวรของแอปและสร้างรายงานความเป็นส่วนตัวจากที่เก็บถาวร

    การผสานรวมแอปพลิเคชัน

    ระบุโทเค็นการตรวจสอบสิทธิ์

    เมื่อแอป Consumer ขออัปเดตการเดินทางจาก Fleet Engine คำขอต้องมีโทเค็นเพื่อการเข้าถึงที่ถูกต้อง ในการให้สิทธิ์และตรวจสอบสิทธิ์คำขอเหล่านี้ SDK ของผู้บริโภคจะเรียกออบเจ็กต์ของคุณที่สอดคล้องกับโปรโตคอล GMTCAuthorization ออบเจ็กต์มีหน้าที่ระบุ โทเค็นเพื่อการเข้าถึงที่จำเป็น

    ในฐานะนักพัฒนาแอป คุณเลือกวิธีสร้างโทเค็นได้ การใช้งานของคุณควรให้ความสามารถในการดำเนินการต่อไปนี้

    • เรียกโทเค็นเพื่อการเข้าถึงซึ่งอาจอยู่ในรูปแบบ JSON จากเซิร์ฟเวอร์ HTTPS
    • แยกวิเคราะห์และแคชโทเค็น
    • โปรดรีเฟรชโทเค็นเมื่อหมดอายุ

    โปรดดูรายละเอียดโทเค็นที่เซิร์ฟเวอร์ Fleet Engine คาดไว้ที่หัวข้อการสร้าง JSON Web Token (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];
    }
    

    ฟังการอัปเดตการเดินทาง

    ตัวอย่างต่อไปนี้แสดงวิธีลงทะเบียน Callback 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 เพื่อรับมือกับ Callback เมื่ออัปเดตสถานะการเดินทางแล้ว

    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 และเกิดข้อผิดพลาดขึ้น คุณสามารถได้รับการ Callback ของ TripModel โดยใช้วิธีการมอบสิทธิ์ tripModel(_:didFailUpdateTripWithError:) Fleet Engine สร้างข้อความแสดงข้อผิดพลาดซึ่งเป็นไปตามมาตรฐานข้อผิดพลาดของ Google Cloud โปรดดูคำจำกัดความของข้อความแสดงข้อผิดพลาดโดยละเอียดและรหัสข้อผิดพลาดทั้งหมดที่หัวข้อเอกสารประกอบเกี่ยวกับข้อผิดพลาดของ Google Cloud

    โดยเฉพาะอย่างยิ่งสำหรับการตรวจสอบการเดินทาง จะต้องมีโทเค็นการตรวจสอบสิทธิ์ที่ถูกต้อง ระบบจะเพิ่ม 401 UNAUTHENTICATED หากไม่มีข้อมูลเข้าสู่ระบบการตรวจสอบสิทธิ์ที่ถูกต้อง เช่น โทเค็นหมดอายุ 403 PERMISSION_DENIED และระบบจะเพิ่มระดับหากผู้โทรไม่มีสิทธิ์เรียกใช้ API ที่เฉพาะเจาะจง (เช่น ผู้ใช้ที่มีบทบาทผู้บริโภคพยายามเรียกใช้ updateTrip) หรือคำขอไม่มีพาหนะ_id/trip_id ที่ถูกต้องในโทเค็น JWT

    ดูข้อมูลเพิ่มเติมได้ที่การจัดการข้อผิดพลาดเกี่ยวกับ SDK ของผู้บริโภค

    การปรับแต่ง UI

    รับและตั้งค่าตัวเลือก UI โพลีไลน์ที่กำหนดเอง

    ตัวอย่างต่อไปนี้แสดงวิธีตั้งค่าตัวเลือก UI ที่กำหนดเองสำหรับเส้นประกอบ

    Swift

    /** MapViewController.swift */
    
    func updatePolylineUIOptions() {
      // The polyline type that you would like to set custom UI options for.
      let customizablePolylineType = GMTCPolylineType.activeRoute
    
      let polylineStyleOptions = GMTCMutablePolylineStyleOptions()
      polylineStyleOptions.strokeWidth = 8.0
      polylineStyleOptions.strokeColor = .blue
      polylineStyleOptions.isVisible = true
      polylineStyleOptions.zIndex = 1000
      polylineStyleOptions.isGeodesic = true
      let coordinator = self.mapView.consumerMapStyleCoordinator
      coordinator.setPolylineStyleOptions(polylineStyleOptions, polylineType:customizablePolylineType)
    }
    

    Objective-C

    /** MapViewController.m */
    
    -   (void)updatePolylineUIOptions {
      // The polyline type that you would like to set custom UI options for.
      GMTCPolylineType customizablePolylineType = GMTCPolylineTypeActiveRoute;
    
      GMTCMutablePolylineStyleOptions *polylineStyleOptions =
          [[GMTCMutablePolylineStyleOptions alloc] init];
      polylineStyleOptions.strokeWidth = 8.0;
      polylineStyleOptions.strokeColor = [UIColor blueColor];
      polylineStyleOptions.isVisible = YES;
      polylineStyleOptions.zIndex = 1000;
      polylineStyleOptions.isGeodesic = YES;
      [[_mapView consumerMapStyleCoordinator] setPolylineStyleOptions:polylineStyleOptions
                                                    polylineType:customizablePolylineType];
    }
    

    รับและตั้งค่าตัวเลือก UI ของตัวทำเครื่องหมายที่กำหนดเอง

    ตัวอย่างต่อไปนี้แสดงวิธีตั้งค่าตัวเลือก UI ที่กำหนดเองสำหรับตัวทำเครื่องหมาย

    Swift

    /** MapViewController.swift */
    
    func updateMarkerUIOptions() {
      let customizableMarkerType = GMTCCustomizableMarkerType.tripVehicle
      let markerStyleOptions = GMTCMutableMarkerStyleOptions()
      markerStyleOptions.groundAnchor = groundAnchor
      markerStyleOptions.isVisible = true
      markerStyleOptions.icon = icon
      markerStyleOptions.zIndex = 100
      markerStyleOptions.isFlat = false
      let coordinator = self.mapView.consumerMapStyleCoordinator
      coordinator.setMarkerStyleOptions(markerStyleOptions, markerType: customizableMarkerType)
    }
    

    Objective-C

    /** MapViewController.m */
    
    -   (void)updateMarkerUIOptions {
      // The marker type that you would like to set custom UI options for.
      GMTCCustomizableMarkerType customizableMarkerType = GMTCCustomizableMarkerTypeTripVehicle;
    
      GMTCMutableMarkerStyleOptions *markerStyleOptions =
          [[GMTCMutableMarkerStyleOptions alloc] init];
      markerStyleOptions.groundAnchor = groundAnchor;
      markerStyleOptions.isVisible = YES;
      markerStyleOptions.icon = icon;
      markerStyleOptions.zIndex = 100;
      markerStyleOptions.isFlat = NO;
    
      [[_mapView consumerMapStyleCoordinator] setMarkerStyleOptions:markerStyleOptions markerType:customizableMarkerType];
    }
    

    การปรับการซูมของกล้อง

    ปุ่ม ตำแหน่งของฉัน ใน Maps SDK สำหรับ iOS จะปรับกล้องไปที่ตำแหน่งอุปกรณ์

    หากมีเซสชันการแชร์เส้นทางที่ใช้งานอยู่ คุณสามารถตั้งกล้องให้อยู่กึ่งกลางเพื่อโฟกัสที่การเดินทาง แทนที่จะโฟกัสแค่ตำแหน่งของอุปกรณ์

    Consumer SDK มีฟีเจอร์กล้องอัตโนมัติ ที่เปิดใช้โดยค่าเริ่มต้น กล้องจะซูมเพื่อโฟกัสที่เส้นทางที่แชร์การเดินทางและจุดอ้างอิงของการเดินทางถัดไป

    AutoCamera

    หากต้องการควบคุมลักษณะการทำงานของกล้องได้มากขึ้น ให้ปิดหรือเปิดใช้ฟีเจอร์กล้องอัตโนมัติโดยใช้พร็อพเพอร์ตี้ isAllowCameraAutoUpdate

    สำหรับการปรับแต่งกล้องเพิ่มเติม โปรดดู Maps SDK สำหรับ iOS การย้ายกล้อง