Bạn có thể sử dụng SDK trình điều khiển để cung cấp tính năng điều hướng và theo dõi nâng cao cho ứng dụng Chuyến đi và Tiến trình đặt hàng. SDK Driver cung cấp thông tin cập nhật về vị trí xe và công việc cho nhóm giải pháp gọi xe và giao hàng theo yêu cầu.
SDK trình điều khiển giúp các dịch vụ của Fleet Engine và dịch vụ tuỳ chỉnh của bạn biết được vị trí và trạng thái của xe. Ví dụ: xe có thể là ONLINE
hoặc OFFLINE
và vị trí của xe sẽ thay đổi khi chuyến đi diễn ra.
Yêu cầu tối thiểu về hệ thống
Điều kiện tiên quyết
Hướng dẫn này giả định ứng dụng của bạn đã triển khai SDK điều hướng, cũng như đã thiết lập và sử dụng được phần phụ trợ Fleet Engine. Tuy nhiên, mã ví dụ cung cấp mẫu về cách thiết lập SDK điều hướng.
Bạn cũng phải bật SDK Maps dành cho iOS trong dự án Google Cloud và Lấy khoá API.
Cấu hình dự án
Sử dụng Trình quản lý gói Swift
Bạn có thể cài đặt SDK trình điều khiển thông qua Trình quản lý gói Swift. Để thêm SDK này, hãy đảm bảo bạn đã xoá mọi phần phụ thuộc hiện có của SDK của trình điều khiển.
Để 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:
-
Mở Xcode
project
hoặcworkspace
, sau đó chuyển đến File > Add Package Dependencies (Tệp > Thêm phần phụ thuộc gói). - Nhập https://github.com/googlemaps/ios-driver-sdk làm URL, nhấn Enter để kéo gói và nhấp vào "Thêm gói".
-
Để 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". -
Trong cửa sổ Choose Package Products (Chọn sản phẩm gói), hãy xác minh rằng
GoogleRidesharingDriver
sẽ được thêm vào mục tiêumain
mà bạn chỉ định. Sau khi hoàn tất, hãy nhấp vào "Thêm gói". -
Để 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:
- 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).
- Để 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 SDK trình điều khiển hiện có đã thêm bằng
CocoaPods
, hãy làm theo các bước sau:
- Đó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
-
Hãy xoá
Podfile
,Podfile.resolved
và Xcodeworkspace
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 trình điều khiển hiện có đã được cài đặt theo cách thủ công, hãy làm theo các bước sau:
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:GoogleRidesharingDriver.xcframework
Trong thư mục cấp cao nhất của dự án Xcode, hãy xoá gói
GoogleRidesharingDriver
.
CocoaPods
Để định cấu hình SDK trình điều khiển 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
Tạo một Podfile cho SDK trình điều khiển và dùng nó để cài đặt API và các phần phụ thuộc của API đó: Tạo một tệp có tên 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. Chỉnh sửa Podfile và thêm các phần phụ thuộc của bạn. Dưới đây là một ví dụ về các phần phụ thuộc:
source "https://github.com/CocoaPods/Specs.git" target 'YOUR_APPLICATION_TARGET_NAME_HERE' do pod 'GoogleRidesharingDriver' end
Dưới đây là một ví dụ bao gồm các nhóm Alpha và Beta cho SDK trình điều khiển dưới dạng phần phụ thuộc:
source "https://cpdc-eap.googlesource.com/ridesharing-driver-sdk.git" source "https://github.com/CocoaPods/Specs.git" target 'YOUR_APPLICATION_TARGET_NAME_HERE' do pod 'GoogleRidesharingDriver' end
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>
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
Đóng Xcode, sau đó mở (nhấp đúp) vào tệp .xcworkspace của dự án để chạy Xcode. Từ thời điểm này trở đi, bạn phải sử dụng tệp .xcworkspace để mở dự án.
Tham khảo Hướng dẫn bắt đầu sử dụng CocoaPods để biết thêm thông tin chi tiết.
Cài đặt XCFramework
XCFramework là một gói nhị phân mà bạn dùng để cài đặt SDK trình điều khiển. 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 Applesilicon. Hướng dẫn này cho biết cách tự thêm XCFramework có chứa SDK trình điều khiển vào dự án và định cấu hình 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:
Giải nén các tệp nén để truy cập vào XCFramework và các tài nguyên.
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.
Hãy tạo một nhóm Khung trong nhóm dự án của bạn nếu chưa có.
Để cài đặt SDK trình điều khiển, hãy kéo tệp
GoogleRidesharingDriver.xcframework
vào dự án của bạn trong Frameworks, Libraries and Embedded Content (Chương trình 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.Kéo
GoogleRidesharingDriver.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ọnCopy items if needed
.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.
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
AudioToolbox.framework
AVFoundation.framework
CoreData.framework
CoreGraphics.framework
CoreLocation.framework
CoreTelephony.framework
CoreText.framework
GLKit.framework
ImageIO.framework
libc++.tbd
libxml2.tbd
libz.tbd
LocalAuthentication.framework
OpenGLES.framework
QuartzCore.framework
SystemConfiguration.framework
UIKit.framework
WebKit.framework
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ả.
Triển khai quá trình uỷ quyền và xác thực
Khi ứng dụng Driver tạo và gửi bản cập nhật đến phần phụ trợ Fleet Engine,
các yêu cầu phải bao gồm mã truy cập hợp lệ. Để cho phép và xác thực các yêu cầu này, SDK trình điều khiển sẽ gọi đối tượng tuân thủ giao thức GMTDAuthorization
. Đối tượng này chịu trách nhiệm cung cấp mã truy cập bắt buộc.
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. Xem Hướng dẫn bắt đầu nhanh về Fleet Engine để biết thêm thông tin.
Ví dụ sau đây triển khai trình cung cấp mã truy cập:
Swift
import GoogleRidesharingDriver
private let providerURL = "INSERT_YOUR_TOKEN_PROVIDER_URL"
class SampleAccessTokenProvider: NSObject, GMTDAuthorization {
private struct AuthToken {
// The cached vehicle token.
let token: String
// Keep track of when the token expires for caching.
let expiration: TimeInterval
// Keep track of the vehicle ID the cached token is for.
let vehicleID: String
}
enum AccessTokenError: Error {
case missingAuthorizationContext
case missingData
}
private var authToken: AuthToken?
func fetchToken(
with authorizationContext: GMTDAuthorizationContext?,
completion: @escaping GMTDAuthTokenFetchCompletionHandler
) {
// Get the vehicle ID from the authorizationContext. This is set by the Driver SDK.
guard let authorizationContext = authorizationContext else {
completion(nil, AccessTokenError.missingAuthorizationContext)
return
}
let vehicleID = authorizationContext.vehicleID
// If appropriate, use the cached token.
if let authToken = authToken,
authToken.expiration > Date.now.timeIntervalSince1970 && authToken.vehicleID == vehicleID
{
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 vehicleTokenKey = "VEHICLE_TOKEN_KEY"
let tokenExpirationKey = "TOKEN_EXPIRATION"
guard let data = data,
let fetchData = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let token = fetchData[vehicleTokenKey] as? String,
let expiration = fetchData[tokenExpirationKey] as? Double
else {
completion(nil, AccessTokenError.missingData)
return
}
strongSelf.authToken = AuthToken(
token: token, expiration: expiration, vehicleID: vehicleID)
completion(token, nil)
}
task.resume()
}
}
Objective-C
#import "SampleAccessTokenProvider.h"
#import <GoogleRidesharingDriver/GoogleRidesharingDriver.h>
// SampleAccessTokenProvider.h
@interface SampleAccessTokenProvider : NSObject<GMTDAuthorization>
@end
static NSString *const PROVIDER_URL = @"INSERT_YOUR_TOKEN_PROVIDER_URL";
// SampleAccessTokenProvider.m
@implementation SampleAccessTokenProvider{
// The cached vehicle token.
NSString *_cachedVehicleToken;
// Keep track of the vehicle ID the cached token is for.
NSString *_lastKnownVehicleID;
// Keep track of when tokens expire for caching.
NSTimeInterval _tokenExpiration;
}
- (void)fetchTokenWithContext:(nullable GMTDAuthorizationContext *)authorizationContext
completion:(nonnull GMTDAuthTokenFetchCompletionHandler)completion {
// Get the vehicle ID from the authorizationContext. This is set by the Driver SDK.
NSString *vehicleID = authorizationContext.vehicleID;
if (!vehicleID) {
NSAssert(NO, @"Vehicle ID is missing from authorizationContext.");
return;
}
// Clear cached vehicle token if vehicle ID has changed.
if (![_lastKnownVehicleID isEqual:vehicleID]) {
_tokenExpiration = 0.0;
_cachedVehicleToken = nil;
}
_lastKnownVehicleID = vehicleID;
// Clear cached vehicletoken if it has expired.
if ([[NSDate date] timeIntervalSince1970] > _tokenExpiration) {
_cachedVehicleToken = nil;
}
// If appropriate, use the cached token.
if (_cachedVehicleToken) {
completion(_cachedVehicleToken, 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 *vehicleTokenKey = @"VEHICLE_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->_cachedVehicleToken = JSONResponse[vehicleTokenKey];
completion(JSONResponse[vehicleTokenKey], 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
Tạo một phiên bản RidesharingDriverAPI
Để tải một thực thể GMTDVehicleReporter
, trước tiên, bạn cần tạo một thực thể GMTDRidesharingDriverAPI
bằng cách sử dụng providerID,vehicleID,driverContext và accessTokenProvider. Mã nhà cung cấp này giống với Mã dự án trên Google Cloud. Bạn có thể truy cập trực tiếp vào thực thể GMTDVehicleReporter
từ
API trình điều khiển.
Ví dụ sau đây sẽ tạo một thực thể GMTDRidesharingDriverAPI
:
Swift
import GoogleRidesharingDriver
private let providerID = "INSERT_YOUR_PROVIDER_ID"
class SampleViewController: UIViewController {
private let mapView: GMSMapView
override func viewDidLoad() {
super.viewDidLoad()
let vehicleID = "INSERT_CREATED_VEHICLE_ID"
let accessTokenProvider = SampleAccessTokenProvider()
let driverContext = GMTDDriverContext(
accessTokenProvider: accessTokenProvider,
providerID: providerID,
vehicleID: vehicleID,
navigator: mapView.navigator)
let ridesharingDriverAPI = GMTDRidesharingDriverAPI(driverContext: driverContext)
}
}
Objective-C
#import "SampleViewController.h"
#import "SampleAccessTokenProvider.h"
#import <GoogleRidesharingDriver/GoogleRidesharingDriver.h>
static NSString *const PROVIDER_ID = @"INSERT_YOUR_PROVIDER_ID";
@implementation SampleViewController {
GMSMapView *_mapView;
}
- (void)viewDidLoad {
NSString *vehicleID = @"INSERT_CREATED_VEHICLE_ID";
SampleAccessTokenProvider *accessTokenProvider =
[[SampleAccessTokenProvider alloc] init];
GMTDDriverContext *driverContext =
[[GMTDDriverContext alloc] initWithAccessTokenProvider:accessTokenProvider
providerID:PROVIDER_ID
vehicleID:vehicleID
navigator:_mapView.navigator];
GMTDRidesharingDriverAPI *ridesharingDriverAPI = [[GMTDRidesharingDriverAPI alloc] initWithDriverContext:driverContext];
}
Nghe các sự kiện VehicleReporter (không bắt buộc)
GMTDVehicleReporter
cập nhật xe định kỳ khi locationTrackingEnabled
ở trạng thái true
. Để phản hồi các bản cập nhật định kỳ này, mọi đối tượng đều có thể đăng ký các sự kiện GMTDVehicleReporter
bằng cách tuân thủ giao thức GMTDVehicleReporterListener
.
Bạn có thể xử lý các sự kiện sau:
vehicleReporter(_:didSucceed:)
Thông báo cho ứng dụng Driver rằng các dịch vụ phụ trợ đã nhận được thông tin cập nhật về vị trí và trạng thái của xe.
vehicleReporter(_:didFail:withError:)
Thông báo cho người nghe rằng không cập nhật được xe. Chỉ cần bật tính năng theo dõi vị trí,
GMTDVehicleReporter
sẽ tiếp tục gửi dữ liệu mới nhất đến phần phụ trợ Fleet Engine.
Ví dụ sau đây xử lý các sự kiện này:
Swift
import GoogleRidesharingDriver
private let providerID = "INSERT_YOUR_PROVIDER_ID"
class SampleViewController: UIViewController, GMTDVehicleReporterListener {
private let mapView: GMSMapView
override func viewDidLoad() {
// Assumes you have implemented the sample code up to this step.
ridesharingDriverAPI.vehicleReporter.add(self)
}
func vehicleReporter(_ vehicleReporter: GMTDVehicleReporter, didSucceed vehicleUpdate: GMTDVehicleUpdate) {
// Handle update succeeded.
}
func vehicleReporter(_ vehicleReporter: GMTDVehicleReporter, didFail vehicleUpdate: GMTDVehicleUpdate, withError error: Error) {
// Handle update failed.
}
}
Objective-C
/*
* SampleViewController.h
*/
@interface SampleViewController : UIViewController<GMTDVehicleReporterListener>
@end
/*
* SampleViewController.m
*/
#import "SampleViewController.h"
#import "SampleAccessTokenProvider.h"
#import <GoogleRidesharingDriver/GoogleRidesharingDriver.h>
static NSString *const PROVIDER_ID = @"INSERT_YOUR_PROVIDER_ID";
@implementation SampleViewController {
GMSMapView *_mapView;
}
- (void)viewDidLoad {
// Assumes you have implemented the sample code up to this step.
[ridesharingDriverAPI.vehicleReporter addListener:self];
}
- (void)vehicleReporter:(GMTDVehicleReporter *)vehicleReporter didSucceedVehicleUpdate:(GMTDVehicleUpdate *)vehicleUpdate {
// Handle update succeeded.
}
- (void)vehicleReporter:(GMTDVehicleReporter *)vehicleReporter didFailVehicleUpdate:(GMTDVehicleUpdate *)vehicleUpdate withError:(NSError *)error {
// Handle update failed.
}
@end
Thêm GMTDvehicleReporter làm trình nghe cho GMSRoadSnappedLocationProvider
Để cung cấp thông tin cập nhật vị trí cho SDK trình điều khiển, bạn phải đặt GMTDVehicleReporter
làm trình nghe của GMSRoadSnappedLocationProvider
.
Swift
import GoogleRidesharingDriver
private let providerID = "INSERT_YOUR_PROVIDER_ID"
class SampleViewController: UIViewController, GMTDVehicleReporterListener {
private let mapView: GMSMapView
override func viewDidLoad() {
// Assumes you have implemented the sample code up to this step.
if let roadSnappedLocationProvider = mapView.roadSnappedLocationProvider {
roadSnappedLocationProvider.add(ridesharingDriverAPI.vehicleReporter)
roadSnappedLocationProvider.startUpdatingLocation()
}
}
}
Objective-C
/*
* SampleViewController.h
*/
@interface SampleViewController : UIViewController<GMTDVehicleReporterListener>
@end
/*
* SampleViewController.m
*/
#import "SampleViewController.h"
#import "SampleAccessTokenProvider.h"
#import <GoogleRidesharingDriver/GoogleRidesharingDriver.h>
static NSString *const PROVIDER_ID = @"INSERT_YOUR_PROVIDER_ID";
@implementation SampleViewController {
GMSMapView *_mapView;
}
- (void)viewDidLoad {
// Assumes you have implemented the sample code up to this step.
[_mapView.roadSnappedLocationProvider addListener:ridesharingDriverAPI.vehicleReporter];
[_mapView.roadSnappedLocationProvider startUpdatingLocation];
}
@end
Bật tính năng theo dõi vị trí
Để bật tính năng theo dõi vị trí, ứng dụng của bạn có thể đặt locationTrackingEnabled
thành
true
trên GMTDVehicleReporter
. GMTDVehicleReporter
tự động gửi
thông tin cập nhật vị trí. Sau khi các dịch vụ trùng khớp và chỉ định xe cho một chuyến đi, GMTDVehicleReporter
sẽ tự động gửi thông tin cập nhật về tuyến đường khi GMSNavigator
đang ở chế độ chỉ đường (khi một điểm đến được đặt thông qua setDestinations
).
Tuyến đường được thiết lập trong quá trình cập nhật chuyến đi sẽ giống với tuyến đường mà người lái xe đang di chuyển trong phiên chỉ đường. Do đó, để tính năng chia sẻ hành trình hoạt động đúng cách, điểm tham chiếu được đặt thông qua setDestinations
phải khớp với đích đến đã đặt trong phần phụ trợ Fleet Engine.
Nếu bạn đặt locationTrackingEnabled
thành true
, thông tin cập nhật về chuyến đi và thông tin về xe sẽ được gửi đến phần phụ trợ của Fleet Engine theo định kỳ dựa trên giá trị được đặt cho locationUpdateInterval
. Nếu bạn đặt locationTrackingEnabled
thành false
, quá trình cập nhật sẽ dừng và yêu cầu cập nhật xe cuối cùng sẽ được gửi đến phần phụ trợ của Fleet Engine để đặt trạng thái xe thành GMTDVehicleState.offline
. Hãy xem updateVehicleState
để biết các điểm đặc biệt cần cân nhắc về cách xử lý lỗi khi locationTrackingEnabled
được đặt thành false
.
Ví dụ sau đây bật tính năng theo dõi vị trí:
Swift
import GoogleRidesharingDriver
private let providerID = "INSERT_YOUR_PROVIDER_ID"
class SampleViewController: UIViewController, GMTDVehicleReporterListener {
private let mapView: GMSMapView
override func viewDidLoad() {
// Assumes you have implemented the sample code up to this step.
ridesharingDriverAPI.vehicleReporter.locationTrackingEnabled = true
}
}
Objective-C
/*
* SampleViewController.m
*/
#import "SampleViewController.h"
#import "SampleAccessTokenProvider.h"
#import <GoogleRidesharingDriver/GoogleRidesharingDriver.h>
static NSString *const PROVIDER_ID = @"INSERT_YOUR_PROVIDER_ID";
@implementation SampleViewController {
GMSMapView *_mapView;
}
- (void)viewDidLoad {
// Assumes you have implemented the sample code up to this step.
ridesharingDriverAPI.vehicleReporter.locationTrackingEnabled = YES;
}
@end
Theo mặc định, khoảng thời gian báo cáo là 10 giây, nhưng bạn có thể thay đổi khoảng thời gian báo cáo này bằng locationUpdateInterval
. Khoảng thời gian tối thiểu được hỗ trợ cho việc cập nhật là 5 giây. Khoảng thời gian tối đa được hỗ trợ cho việc cập nhật là 60 giây. Việc cập nhật thường xuyên hơn có thể khiến các yêu cầu và lỗi bị chậm hơn.
Cập nhật trạng thái xe
Ví dụ sau đây cho thấy cách đặt trạng thái xe thành ONLINE
. Hãy xem updateVehicleState
để biết thông tin chi tiết.
Swift
import GoogleRidesharingDriver
private let providerID = "INSERT_YOUR_PROVIDER_ID"
class SampleViewController: UIViewController, GMTDVehicleReporterListener {
private let mapView: GMSMapView
override func viewDidLoad() {
// Assumes you have implemented the sample code up to this step.
ridesharingDriverAPI.vehicleReporter.update(.online)
}
}
Objective-C
#import "SampleViewController.h"
#import "SampleAccessTokenProvider.h"
#import <GoogleRidesharingDriver/GoogleRidesharingDriver.h>
static NSString *const PROVIDER_ID = @"INSERT_YOUR_PROVIDER_ID";
@implementation SampleViewController {
GMSMapView *_mapView;
}
- (void)viewDidLoad {
// Assumes you have implemented the sample code up to this step.
[ridesharingDriverAPI.vehicleReporter
updateVehicleState:GMTDVehicleStateOnline];
}
@end
Lỗi update_mask
có thể xảy ra khi mặt nạ trống và thường xảy ra trong lần cập nhật đầu tiên sau khi khởi động. Ví dụ sau cho biết cách xử lý lỗi này:
Swift
import GoogleRidesharingDriver
class VehicleReporterListener: NSObject, GMTDVehicleReporterListener {
func vehicleReporter(
_ vehicleReporter: GMTDVehicleReporter,
didFail vehicleUpdate: GMTDVehicleUpdate,
withError error: Error
) {
let fullError = error as NSError
if let innerError = fullError.userInfo[NSUnderlyingErrorKey] as? NSError {
let innerFullError = innerError as NSError
if innerFullError.localizedDescription.contains("update_mask cannot be empty") {
emptyMaskUpdates += 1
return
}
}
failedUpdates += 1
}
override init() {
emptyMaskUpdates = 0
failedUpdates = 0
}
}
Objective-C
#import "VehicleReporterListener.h"
#import <GoogleRidesharingDriver/GoogleRidesharingDriver.h>
@implementation VehicleReporterListener {
NSInteger emptyMaskUpdates = 0;
NSInteger failedUpdates = 0;
}
- (void)vehicleReporter:(GMTDVehicleReporter *)vehicleReporter
didFailVehicleUpdate:(GMTDVehicleUpdate *)vehicleUpdate
withError:(NSError *)error {
for (NSError *underlyingError in error.underlyingErrors) {
if ([underlyingError.localizedDescription containsString:@"update_mask cannot be empty"]) {
emptyMaskUpdates += 1;
return;
}
}
failedUpdates += 1
}
@end
Tắt thông báo cập nhật vị trí và lấy xe ngoại tuyến
Ứng dụng của bạn có thể tắt bản cập nhật và đưa xe vào chế độ ngoại tuyến. Ví dụ: khi ca làm việc của người lái xe kết thúc, ứng dụng của bạn có thể đặt locationTrackingEnabled
thành false
.
Khi bạn tắt bản cập nhật, trạng thái của xe cũng sẽ được đặt thành OFFLINE
trên phần phụ trợ của Fleet Engine.
Swift
vehicleReporter.locationTrackingEnabled = false
Objective-C
_vehicleReporter.locationTrackingEnabled = NO;