Skip to main content

Usage Examples for iOS apps

1. Documentation​

In Swift, the SDK is used through the TelematicsSDKios class. In Objective-C, use the TelematicsSDKObjC class, which exposes the same functionality with completion blocks and Objective-C compatible types.


2. Usage​

Here you have some usage examples of the TelematicsSDK.

A typical integration follows this flow:

  1. Initialize the SDK with the user's tokens (2.1).
  2. Register the vehicle (2.3).
  3. Make sure all permissions are granted (2.5).
  4. Start the telematics service (2.6).

2.1 Initialization​

Initialize the SDK when your application starts.

The SDK is initialized with the access token and refresh token of the authenticated user, together with the base URL of the telematics platform provided by Sentilant. These values are obtained by your application from your authentication backend.

OptionRequiredDescription
baseURLYesBase URL of the telematics platform. A host (telematics.example.com) or a full URL (https://telematics.example.com) is accepted.
tokenYesAccess token of the user.
tokenExpiresNoExpiry of the access token, as an ISO 8601 timestamp (e.g. 2026-11-03T12:43:29.562522Z).
refreshTokenNoRefresh token of the user. Supplying it enables automatic token renewal.
refreshTokenExpiresNoExpiry of the refresh token, as an ISO 8601 timestamp.

When a refresh token is supplied, the SDK renews the access token on its own, before it expires or when the server rejects it. Your application does not need to provide new tokens while the session remains valid. Without a refresh token, the SDK uses the access token as-is until it stops working.

TelematicsTokenInitOptions throws a TelematicsInitOptionsError if the base URL or the token is empty, if the base URL is not valid, or if an expiry is not a valid ISO 8601 timestamp.

After a successful initialization, the SDK retrieves the authenticated user automatically. No additional login call is required.

The SDK cannot renew tokens while the app is not running. Choose a refresh token lifetime long enough for your usage pattern, and handle re-authentication as described in 2.2 Session lifecycle.

import Foundation
import TelematicsSDK

let sdk = TelematicsSDKios()

do {
let options = try TelematicsTokenInitOptions(
baseURL: "TELEMATICS_BASE_URL",
token: "ACCESS_TOKEN",
tokenExpires: "ACCESS_TOKEN_EXPIRES",
refreshToken: "REFRESH_TOKEN",
refreshTokenExpires: "REFRESH_TOKEN_EXPIRES"
)

sdk.initSDK(options: options) { (error: TelematicsSDKException?) in
if let error = error {
// Handle initialization error
} else {
// Initialization succeeded
}
}
} catch {
// Invalid options (TelematicsInitOptionsError)
}

2.2 Session lifecycle​

Authentication invalidated​

Set the onAuthenticationInvalidated callback to be notified when the SDK can no longer authenticate.

ReasonObjective-C valueSession destroyedDescription
.refreshTokenExpired0YesThe refresh token expired.
.refreshTokenRejected1YesThe server rejected the refresh token.
.accountInactive2NoThe user account is inactive. The credentials remain valid.
.accessDenied3NoThe server refused access. The credentials remain valid.
.accessTokenRejected4YesThe server rejected the access token of a session without a refresh token.

reason.invalidatesSession is true when the session was destroyed. In that case the SDK has already stopped telemetry and removed the user and vehicle. To restore the session:

  1. obtain new tokens and call initSDK again;
  2. set the vehicle again (setVehicle);
  3. call startTelematicsService again. Telemetry does not restart by itself.

Data collected before the invalidation is kept on the device and is uploaded automatically once the session is restored.

import Foundation
import TelematicsSDK

sdk.onAuthenticationInvalidated = { (reason: TelematicsAuthInvalidationReason) in
if reason.invalidatesSession {
// Session destroyed: obtain new tokens, call initSDK, setVehicle and startTelematicsService
} else {
// Access refused (e.g. inactive account): the session is kept
}
}

Session state​

getSessionState() returns what the SDK knows about its session, without making any request. It can be called from any thread.

StatusObjective-C valueDescription
.notAuthenticated0No credentials: the SDK was never initialized, or the user logged out.
.verified1The server accepted the current access token (at lastVerifiedAt).
.unverified2There are credentials, but the server has not confirmed them yet.
.denied3The server refused access (e.g. inactive account). New credentials would not help.
.invalid4The server rejected the session. New tokens must be provided through initSDK.

The returned TelematicsSessionState also exposes:

  • invalidationReason: the reason for the .invalid or .denied status, or nil.
  • isAutoRenewing: true if the SDK holds a refresh token and renews the access token on its own.
  • recoverableUntil: until when the session can be kept alive without new tokens (ISO 8601), or nil if unknown.
  • lastVerifiedAt: when the server last accepted the access token (ISO 8601), or nil.

The status reflects the last answer from the server, not a live check.

import Foundation
import TelematicsSDK

let state = sdk.getSessionState()

if state.status == .invalid {
// Obtain new tokens and call initSDK again
}

Current user​

Retrieve the identifier and the name of the authenticated user using getCurrentUserInfo:

import Foundation
import TelematicsSDK

sdk.getCurrentUserInfo(
success: { (userId: Int, userName: String) in
// Current user fetched successfully
},
failure: { (error: TelematicsSDKException) in
// Handle error fetching current user
}
)

Logout​

logout() ends the session of the current user. It:

  1. stops telemetry, if the telematics service is running;
  2. tries to send the telemetry data still stored on the device to the server;
  3. ends the session, removing the credentials, the user and the vehicle from the SDK.

Data that could not be sent before the session ended (for example, without network) is kept on the device and is sent after the next successful initSDK.

After logout, the session state is .notAuthenticated. To use the SDK again, call initSDK with the tokens of the new session.

sdk.logout()

2.3 Vehicle Management​

Set the user vehicle using the setVehicle method. The vehicle type, add reason and fuel type are identifier codes returned by getVehicleTypes, getAddVehicleReasons and getFuelTypes. Each of these methods returns a dictionary where the key is the name and the value is the identifier code. In Swift these methods are async; in Objective-C they use a completion block.

import Foundation
import TelematicsSDK

Task {
let fuelTypes = await sdk.getFuelTypes() // e.g. ["Diesel": 1, "Gasoline": 2, ...]
let vehicleTypes = await sdk.getVehicleTypes()
let addReasons = await sdk.getAddVehicleReasons()

guard let fuelType = fuelTypes.values.first,
let vehicleType = vehicleTypes.values.first,
let addReason = addReasons.values.first else {
return
}

sdk.setVehicle(plate: "plate123", internalPlate: "internalPlate", type: vehicleType, addReason: addReason, fuelType: fuelType) { (result: TelematicsSDKException?) in
DispatchQueue.main.async {
if let result = result {
// Handle error setting vehicle
} else {
// Vehicle set successfully
}
}
}
}

If the vehicle already exists, it can be set by its license plate only. The vehicle details are returned on success, or an error if no vehicle with that plate exists:

import Foundation
import TelematicsSDK

sdk.setVehicle(
plate: "plate123",
success: { (vehicle: TelematicsVehicleDetails) in
// Vehicle set successfully
},
failure: { (error: TelematicsSDKException) in
// Vehicle not found or error setting vehicle
}
)

Other vehicle methods:

  • getCurrentVehicleInfo(success:failure:): returns the details of the current vehicle, or an error if no vehicle is set.
  • clearVehicle(): removes the current vehicle from the SDK.

2.4 Report vehicle kms​

Report the vehicle's current kilometers using the reportKilometers method:

import Foundation
import TelematicsSDK

sdk.reportKilometers(kilometers: 1200, observations: "Routine check") { (result: TelematicsSDKException?) in
DispatchQueue.main.async {
if let result = result {
// Handle error reporting kilometers
} else {
// Kilometers reported successfully
}
}
}

Other kilometer methods:

  • correctKilometers(kilometers:observations:correctionCount:callback:): corrects the odometer reading, applying the value to the given number of past records.
  • getEstimatedMileage(): returns the estimated current mileage in kilometers, or -1 if it cannot be estimated.

2.5 Permission Handling​

Check the permissions manually using the checkPermissions and getRequiredPermissions methods:

import Foundation
import TelematicsSDK

let missingPermissions = sdk.checkPermissions()

if missingPermissions.isEmpty {
// All required permissions are granted
} else {
// Request missing permissions
}

let requiredPermissions = sdk.getRequiredPermissions()

// requiredPermissions = ["Location Permission", "Background Location Permission", "Motion and Fitness Permission"]

To react to permission changes while the app is running, see 2.12 Permission Callbacks.

2.6 Telematics Service​

Start and stop the telematics service as needed. Before starting, the SDK validates that the session is valid, that a user and a vehicle are set and that all permissions are granted. If any of these checks fails, the service is not started and the callback receives an error. In Swift, startTelematicsService is async.

import Foundation
import TelematicsSDK

// Start the service
Task {
await sdk.startTelematicsService { (result: TelematicsSDKException?) in
DispatchQueue.main.async {
if let result = result {
// Handle error starting telematics service
} else {
// Telematics service successfully started
}
}
}
}

// Check if the service is running
let isRunning = sdk.isTelematicsServiceRunning()

// Stop the service
sdk.stopTelematicsService { (result: TelematicsSDKException?) in
DispatchQueue.main.async {
if let result = result {
// Handle error stopping telematics service
} else {
// Telematics service successfully stopped
}
}
}

setServiceCode(serviceCode:callback:) changes the service code used by the telematics service.

2.7 Attention Detection​

While the telematics service is running, the SDK can detect on the device, using a machine learning model, when the user is handling the phone while driving. Each detection produces an attention event.

  • Attention detection is enabled by default and runs only while the telematics service is running, including when telemetry is restored after the app is relaunched.
  • Use setAttentionDetectionEnabled(false) to disable it. The choice is persisted and applies immediately if the service is running. While disabled, no detection work is done, which reduces battery usage. Telemetry collection is not affected.
  • Attention events are stored on the device and uploaded to the platform automatically, in the same way as telemetry data.
  • Each event covers a 10 second window. A new window starts every 5 seconds, so a continuous distraction produces several events.

Set the onAttentionEvent callback to receive the events in your application. It is called on the main thread. Setting a new callback replaces the previous one; set it to nil to stop receiving events. Events detected while no callback is set are not delivered later.

import Foundation
import TelematicsSDK

sdk.onAttentionEvent = { (event: TelematicsAttentionEvent) in
// event.type -> .phoneDistraction
// event.startDate / event.endDate -> window
// event.confidence -> 0...1
}

// Enable or disable attention detection
sdk.setAttentionDetectionEnabled(true)
let enabled = sdk.isAttentionDetectionEnabled

TelematicsAttentionEvent fields:

FieldTypeDescription
idUUIDUnique identifier of the event.
typeTelematicsAttentionEventTypeEvent type. Currently .phoneDistraction.
startTimestampMs / endTimestampMsInt64Start and end of the window, epoch milliseconds. Also available as startDate / endDate.
confidenceDoubleDetection confidence, from 0 to 1.
averageSpeedMpsDouble?Mean GPS speed during the window in m/s.
latitude / longitudeDouble?Position of the first valid GPS fix in the window.
horizontalAccuracyMDouble?Horizontal accuracy of that fix in meters.
locationTimestampMsInt64?Time of that fix, epoch milliseconds.
detectorVersionStringIdentifier of the detector that produced the event.

toDictionary() returns the event as a dictionary with the same keys used on Android and React Native. In Objective-C, TSDKAttentionEventObjC exposes the same fields (optional values as NSNumber) and the dictionary in dictionary.

2.8 Trips​

Retrieves the trips list for an optional date range.

startTs and endTs are provided as Date/NSDate and are sent to the backend as UTC ISO-8601 query parameters. If both values are nil, the SDK calls the endpoint without date filters and tries to return all trips.

import Foundation
import TelematicsSDK

// Example: fetch trips from the last 7 days until now
let endTs = Date()
let startTs = Calendar.current.date(byAdding: .day, value: -7, to: endTs)

// If you want no filtering, pass nil for both.
sdk.getTripsList(
startTs: startTs,
endTs: endTs,
success: { trips in
DispatchQueue.main.async {
// trips: [TelematicsTripResume]
print("Trips count: \(trips.count)")
}
},
failure: { error in
DispatchQueue.main.async {
print("Failed to get trips list: \(error)")
}
}
)

To retrieve the details of a single trip, use getTripById(tripId:includeSamples:success:failure:), which returns a TelematicsTripDetails. Set includeSamples to true to include the trip samples in the response.

2.9 User metrics summary​

Retrieves the user metrics summary for an optional date range.

startTs and endTs are provided as Date/NSDate and are sent to the backend as UTC ISO-8601 query parameters. If both values are nil, the SDK calls the endpoint without date filters.

import Foundation
import TelematicsSDK

// Example: fetch metrics for the current month
let calendar = Calendar.current
let now = Date()

let startOfMonth = calendar.date(from: calendar.dateComponents([.year, .month], from: now))
let endTs = now

sdk.getMetricsSummary(
startTs: startOfMonth,
endTs: endTs,
success: { metrics in
DispatchQueue.main.async {
// metrics: TelematicsMetricsSummary
print("Metrics summary: \(metrics)")
}
},
failure: { error in
DispatchQueue.main.async {
print("Failed to get metrics summary: \(error)")
}
}
)

getActivityMetricsSummary(startTs:endTs:success:failure:) returns the activity metrics summary (TelematicsActivityMetricsSummary) for an optional date range.

2.10 Telematics Periods​

Retrieve the telematics periods within an optional date range. isProcessed filters by processed state and can be nil.

  • getTelematicsPeriods(startTs:endTs:isProcessed:page:success:failure:): one page of periods (TelematicsPeriodsPage). page can be nil to use the default page. An overload without page is also available.
  • getAllTelematicsPeriods(startTs:endTs:isProcessed:success:failure:): the full list of periods.
  • getTelematicsPeriod(id:success:failure:): the details of a single period.
import Foundation
import TelematicsSDK

let endTs = Date()
let startTs = Calendar.current.date(byAdding: .month, value: -1, to: endTs)

sdk.getAllTelematicsPeriods(
startTs: startTs,
endTs: endTs,
isProcessed: nil,
success: { (periods: [TelematicsPeriod]) in
// Telematics periods fetched successfully
},
failure: { (error: TelematicsSDKException) in
// Handle error fetching telematics periods
}
)

2.11 Manual Events​

Manual events allow the user to mark, during a trip, the moment a specific driving event happened (for example, a hard braking or a distraction).

The SDK records the event type with the current time and the latest location collected by the SDK, and sends it to the server. The event is therefore meant to be inserted while a trip is being recorded.

Later, when analysing the trip, the manual events can be compared with the events detected automatically by the SDK. For example, if a manual distraction event is marked at minute 10 of a trip, you can check whether a distraction event was also detected at that minute, and use this comparison to validate the trip and assess the reliability of the event detection.

Register a manual event using insertManualEvent. The available types are defined in TelematicsManualEventType: .abruptAccelerationHighSpeed, .abruptAccelerationLowSpeed, .hardBrakingHighSpeed, .hardBrakingLowSpeed, .hardCornering, .speeding, .distraction, .walking, .driving, .stopped, .tripStart and .tripEnd.

import Foundation
import TelematicsSDK

Task {
await sdk.insertManualEvent(eventType: .hardBrakingHighSpeed) { (result: TelematicsSDKException?) in
if let result = result {
// Handle error inserting the event
}
}
}

2.12 Permission Callbacks​

The SDK exposes three callbacks that allow the application to react to permission changes and telemetry interruptions while the app is running. See Permissions Runtime Behavior for details.

import Foundation
import TelematicsSDK

// Register iOS permission & telemetry callbacks
sdk.onPermissionsMissing = { (missingPermissions: [String]) in
DispatchQueue.main.async {
if missingPermissions.isEmpty {
// Permissions are now consistent with SDK requirements
} else {
// One or more mandatory permissions are missing
}
}
}

sdk.onPermissionsLostWhileRunning = { (lostAt: Date, missingPermissions: [String]) in
DispatchQueue.main.async {
// Telemetry was interrupted due to permission removal while it was expected to be running

// lostAt indicates when telemetry became invalid
// missingPermissions contains the permissions that were removed
}
}

sdk.onTelemetryGapDetected = { (from: Date, to: Date) in
DispatchQueue.main.async {
// A telemetry interruption (gap) was detected
// • from: moment telemetry stopped producing samples
// • to: moment telemetry resumed

// Telemetry should be already running again at this point
}
}

2.13 Errors​

In Swift, errors are delivered as TelematicsSDKException or one of its subclasses. In Objective-C, they are delivered as TSDKErrorObjC.

ExceptionWhen
TelematicsSDKNotAuthenticatedExceptionThe SDK has no valid session.
TelematicsSDKSessionExpiredExceptionThe session expired (subclass of TelematicsSDKNotAuthenticatedException).
TelematicsSDKMissingUserExceptionNo user is set.
TelematicsSDKMissingVehicleExceptionNo vehicle is set.
TelematicsSDKMissingPermissionExceptionOne or more required permissions are not granted.