Bắt đầu với SDK người tiêu dùng dành cho iOS

Bạn có thể sử dụng SDK người tiêu dùng để tạo và chạy một ứng dụng cơ bản dành cho người tiêu dùng, được tích hợp với các dịch vụ phụ trợ Giải pháp gọi xe và giao hàng theo yêu cầu. Bạn có thể tạo ứng dụng Chuyến đi và Tiến trình đặt hàng. Ứng dụng này có thể hiển thị chuyến đi đang hoạt động, phản hồi thông tin cập nhật về chuyến đi và xử lý các lỗi về chuyến đi.

Vì SDK người dùng có cấu trúc mô-đun, nên bạn có thể sử dụng các phần của API mà bạn muốn dùng cho ứng dụng cụ thể của mình và tích hợp các phần đó với API của riêng bạn, các dịch vụ phụ trợ do Fleet Engine cung cấp và các API bổ sung của Nền tảng Google Maps.

Yêu cầu tối thiểu về hệ thống

  • Thiết bị di động phải chạy iOS 14 trở lên.
  • Xcode phiên bản 15 trở lên.
  • Cấu hình dự án

    Trình quản lý gói Swift

    Bạn có thể cài đặt SDK người dùng thông qua Trình quản lý gói Swift. Để thêm SDK, hãy đảm bảo bạn đã xoá mọi phần phụ thuộc hiện có của SDK Người tiêu dùng.

    Để thêm SDK vào một dự án mới hoặc hiện có, hãy làm theo các bước sau:

    1. Mở Xcode project hoặc workspace, sau đó chuyển đến File > Add Package Dependencies (Tệp > Thêm phần phụ thuộc gói).
    2. Nhập https://github.com/googlemaps/ios-consumer-sdk làm URL, nhấn Enter để kéo gói và nhấp vào "Thêm gói".
    3. Để cài đặt một version cụ thể, hãy đặt trường Quy tắc phần phụ thuộc thành một trong các tuỳ chọn dựa trên phiên bản. Đối với dự án mới, bạn nên chỉ định phiên bản mới nhất và sử dụng tuỳ chọn "Phiên bản chính xác". Sau khi hoàn tất, hãy nhấp vào "Thêm gói".
    4. Trong cửa sổ Choose Package Products (Chọn sản phẩm gói), hãy xác minh rằng GoogleRidesharingConsumer sẽ được thêm vào mục tiêu main mà bạn chỉ định. Sau khi hoàn tất, hãy nhấp vào "Thêm gói".
    5. Để xác minh việc cài đặt, hãy chuyển đến ngăn General của mục tiêu. Trong Frameworks, Libraries và Embedded Content (Nội dung được nhúng), bạn sẽ thấy các gói đã cài đặt. Bạn cũng có thể xem phần "Package Dependencies" (Phần phụ thuộc của gói) trong "Project Navigator" (Trình điều hướng dự án) để xác minh gói và phiên bản của gói đó.

    Để cập nhật package cho một dự án hiện có, hãy làm theo các bước sau:

    1. Trong Xcode, hãy chuyển đến "File > Packages > Update To New Package Versions" (Tệp > Gói > Cập nhật lên phiên bản gói mới nhất).
    2. Để xác minh quá trình cài đặt, hãy chuyển đến phần Package Dependencies (Phần phụ thuộc của gói) trong Project Navigator (Trình điều hướng dự án) để xác minh gói và phiên bản của gói đó.

    Để xoá các phần phụ thuộc hiện có của SDK người tiêu dùng đã thêm bằng CocoaPods, hãy làm theo các bước sau:

    1. Đóng không gian làm việc Xcode của bạn. Mở cửa sổ dòng lệnh rồi thực thi lệnh sau:
      sudo gem install cocoapods-deintegrate cocoapods-clean 
      pod deintegrate 
      pod cache clean --all
    2. Hãy xoá Podfile, Podfile.resolved và Xcode workspace nếu bạn không sử dụng chúng cho bất kỳ sản phẩm nào khác ngoài CocoaPods.

    Để xoá SDK Người tiêu dùng hiện có đã được cài đặt theo cách thủ công, hãy làm theo các bước sau:

    1. Trong phần cài đặt cấu hình của dự án Xcode, hãy tìm Frameworks, Thư viện và Nội dung được nhúng. Sử dụng dấu trừ(-) để xoá khung sau:

      • GoogleRidesharingConsumer.xcframework
    2. Trong thư mục cấp cao nhất của dự án Xcode, hãy xoá gói GoogleRidesharingConsumer.

    CocoaPods

    Để định cấu hình SDK người dùng bằng CocoaPods, bạn cần có các mục sau:

    • Công cụ CocoaPods: Để cài đặt công cụ này, hãy mở cửa sổ dòng lệnh và chạy lệnh sau.

      sudo gem install cocoapods
      

    Tham khảo Hướng dẫn bắt đầu sử dụng CocoaPods để biết thêm thông tin chi tiết.

    1. Tạo một Podfile cho SDK người tiêu dùng và sử dụng nó để cài đặt API và các phần phụ thuộc của API đó. Trước tiên, hãy tạo một tệp có tên là Podfile trong thư mục dự án của bạn. Tệp này xác định các phần phụ thuộc của dự án. Sau đó, hãy chỉnh sửa Podfile và thêm phần phụ thuộc. Dưới đây là một ví dụ bao gồm các phần phụ thuộc:

        source "https://github.com/CocoaPods/Specs.git"
      
        target 'YOUR_APPLICATION_TARGET_NAME_HERE' do
          pod 'GoogleRidesharingConsumer'
        end
      
    2. Lưu Podfile. Mở cửa sổ dòng lệnh rồi chuyển đến thư mục chứa Podfile:

      cd <path-to-project>
      
    3. Chạy lệnh nhóm cài đặt. Thao tác này sẽ cài đặt các API được chỉ định trong Podfile, cùng với mọi phần phụ thuộc mà các API đó có thể có.

      pod install
      
    4. Đóng Xcode rồi mở (nhấp đúp) vào tệp .xcworkspace của dự án để chạy Xcode. Để mở dự án vào lúc khác, hãy sử dụng tệp .xcworkspace.

    Cài đặt theo cách thủ công

    XCFramework là một gói nhị phân mà bạn dùng để cài đặt SDK Người dùng. Bạn có thể sử dụng gói này trên nhiều nền tảng, bao gồm cả các máy sử dụng chipset M1. Hướng dẫn này cho biết cách thêm thủ công XCFramework có chứa SDK người tiêu dùng vào dự án của bạn và định cấu hình các chế độ cài đặt bản dựng trong Xcode.

    Tải tệp nhị phân SDK và các tài nguyên xuống:

    1. Giải nén các tệp nén để truy cập vào XCFramework và các tài nguyên.

    2. Khởi động Xcode rồi mở một dự án hiện có hoặc tạo một dự án mới. Nếu bạn mới sử dụng iOS, hãy tạo một dự án mới và chọn mẫu Ứng dụng iOS.

    3. Hãy tạo một nhóm Khung trong nhóm dự án của bạn nếu chưa có.

    4. Để cài đặt SDK Người dùng, hãy kéo tệp GoogleRidesharingConsumer.xcframework vào dự án của bạn trong phần Frameworks, Libraries and Embedded Content (Khung, Thư viện và Nội dung được nhúng). Khi được nhắc, hãy chọn Sao chép các mục nếu cần.

    5. Kéo GoogleRidesharingConsumer.bundle đã tải xuống vào thư mục cấp cao nhất của dự án Xcode. Khi được nhắc, hãy chọn Copy items if needed.

    6. Chọn dự án của bạn trên Project Navigator rồi chọn mục tiêu của ứng dụng.

    7. Mở thẻ Build Phases (Giai đoạn bản dựng), và trong Link Binary with Libraries (Liên kết nhị phân với thư viện), hãy thêm các khung và thư viện sau đây nếu chưa có:

      • 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. Chọn dự án của bạn thay vì một mục tiêu cụ thể rồi mở thẻ Build Settings (Cài đặt bản dựng). Trong mục Cờ trình liên kết khác, hãy thêm -ObjC cho cả gỡ lỗi và phát hành. Nếu các chế độ cài đặt này không xuất hiện, hãy thay đổi bộ lọc trong thanh Cài đặt bản dựng từ Cơ bản thành Tất cả.

    Thêm tệp kê khai quyền riêng tư của Apple

    1. Tải gói Tệp kê khai quyền riêng tư cho SDK người tiêu dùng xuống cho iOS: GoogleRidesharingConsumerPrivacy.
    2. Giải nén tệp để truy cập vào GoogleRidesharingConsumerPrivacy.bundle.
    3. Thêm GoogleRidesharingConsumerPrivacy.bundle vào trình điều hướng của Dự án Xcode bằng một trong các phương thức này. Hãy nhớ chọn hộp "Thêm vào mục tiêu" cho mục tiêu của ứng dụng. Sau khi thêm, tệp PrivacyInfo sẽ xuất hiện trong trình điều hướng của dự án và bạn có thể kiểm tra các giá trị.
    4. Ảnh chụp màn hình thông tin quyền riêng tư của Xcode
    5. Xác minh rằng tệp kê khai quyền riêng tư đã được thêm vào bằng cách tạo bản lưu trữ của ứng dụng và tạo báo cáo về quyền riêng tư từ bản lưu trữ.

    Tích hợp ứng dụng

    Cung cấp mã thông báo xác thực

    Khi ứng dụng Người tiêu dùng của bạn yêu cầu Fleet Engine thông tin cập nhật về chuyến đi, các yêu cầu đó phải bao gồm mã truy cập hợp lệ. Để uỷ quyền và xác thực những yêu cầu này, SDK Người tiêu dùng sẽ gọi đối tượng của bạn tuân theo giao thức GMTCAuthorization. Đối tượng này chịu trách nhiệm cung cấp mã truy cập cần thiết.

    Là nhà phát triển ứng dụng, bạn chọn cách tạo mã thông báo. Quá trình triển khai của bạn sẽ cung cấp khả năng thực hiện những việc sau:

    • Tìm nạp một mã truy cập, có thể ở định dạng JSON, từ máy chủ HTTPS.
    • Phân tích cú pháp và lưu mã thông báo vào bộ nhớ đệm.
    • Hãy làm mới mã thông báo khi hết hạn.

    Để biết thông tin chi tiết về mã thông báo mà máy chủ Fleet Engine dự kiến, hãy xem phần Tạo mã thông báo web JSON (JWT) để uỷ quyền.

    Mã nhà cung cấp giống với mã dự án trên Google Cloud. Để biết thêm thông tin, hãy xem bài viết Làm quen với Fleet Engine.

    Ví dụ sau đây triển khai trình cung cấp mã truy cập:

    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
    

    Khởi chạy ứng dụng

    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
    

    Tích hợp chế độ xem bản đồ

    Khởi chạy chế độ xem bản đồ

    Ví dụ sau đây cho thấy cách khởi tạo 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
    

    Xử lý sự kiện xem bản đồ

    Ví dụ sau cho biết cách triển khai uỷ quyền để xử lý các sự kiện trạng thái của khách hàng.

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

    Chia sẻ hành trình

    Bắt đầu chuyến đi mới khi chế độ xem đã tải

    Ví dụ sau đây cho thấy cách bắt đầu chia sẻ hành trình ngay sau khi tải khung hiển thị. Bạn có thể thu thập tất cả hoạt động đầu vào của người dùng (chẳng hạn như vị trí trả xe và nhận hàng) từ ViewController, sau đó tạo một ViewController mới để bắt đầu trực tiếp hành trình chia sẻ.

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

    Huỷ chuyến đi đang diễn ra

    Ví dụ sau đây cho biết cách đặt lại chuyến đi hiện tại.

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

    Nghe thông tin cập nhật về chuyến đi

    Ví dụ sau đây cho thấy cách đăng ký lệnh gọi lại 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];
      ...
    }
    

    Ví dụ sau đây cho biết cách huỷ đăng ký lệnh gọi lại tripModel.

    Swift

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

    Objective-C

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

    Ví dụ sau đây cho thấy cách triển khai giao thức GMTCTripModelSubscriber để xử lý các lệnh gọi lại khi trạng thái chuyến đi được cập nhật.

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

    Xử lý lỗi

    Nếu đã đăng ký TripModel và xảy ra lỗi, bạn có thể nhận được lệnh gọi lại của tripModel bằng cách triển khai phương thức uỷ quyền tripModel(_:didFailUpdateTripWithError:). Fleet Engine đã tạo thông báo lỗi theo tiêu chuẩn về lỗi của Google Cloud. Để xem định nghĩa chi tiết về thông báo lỗi và tất cả các mã lỗi, hãy tham khảo tài liệu về Lỗi trên Google Cloud.

    Cụ thể, để giám sát chuyến đi, tính năng này yêu cầu cung cấp một mã thông báo xác thực hợp lệ. 401 UNAUTHENTICATED sẽ được kích hoạt nếu không có thông tin xác thực hợp lệ, chẳng hạn như mã thông báo đã hết hạn.403 PERMISSION_DENIED sẽ được nâng lên nếu phương thức gọi không có quyền gọi một api cụ thể (ví dụ: người dùng có vai trò người dùng cố gắng gọi updateTrip) hoặc yêu cầu không có xe_id/trip_id hợp lệ trong mã thông báo JWT.

    Để biết thêm thông tin, hãy xem bài viết Xử lý lỗi SDK người tiêu dùng.

    Tuỳ chỉnh giao diện người dùng

    Tải và đặt các tuỳ chọn cho giao diện người dùng nhiều đường tuỳ chỉnh

    Ví dụ sau đây cho thấy cách thiết lập các tuỳ chọn tuỳ chỉnh trên giao diện người dùng cho hình nhiều đường.

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

    Nhận và đặt các lựa chọn cho giao diện người dùng của điểm đánh dấu tuỳ chỉnh

    Ví dụ sau đây cho thấy cách thiết lập các tuỳ chọn tuỳ chỉnh trên giao diện người dùng cho điểm đánh dấu.

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

    Điều chỉnh mức thu phóng của máy ảnh

    Nút Vị trí của tôi trong SDK bản đồ dành cho iOS đặt máy ảnh vào vị trí của thiết bị.

    Nếu có một phiên Chia sẻ hành trình đang hoạt động, bạn có thể căn giữa camera để lấy nét vào hành trình thay vì chỉ tập trung vào vị trí của thiết bị.

    SDK người dùng cung cấp tính năng máy ảnh tự động được bật theo mặc định. Máy ảnh sẽ thu phóng để tập trung vào tuyến đường chia sẻ hành trình và điểm tham chiếu chuyến đi tiếp theo.

    AutoCamera

    Nếu cần nhiều quyền kiểm soát hơn đối với hoạt động của máy ảnh, bạn có thể tắt hoặc bật tính năng máy ảnh tự động bằng cách sử dụng thuộc tính isAllowCameraAutoUpdate.

    Để biết thêm các tùy chỉnh máy ảnh, hãy xem SDK Bản đồ dành cho iOS Di chuyển máy ảnh.