Links

iOS

This section describes how to integrate DriveKit into an iOS mobile application.

Requirements

DriveKit is developed with the Swift 5 language and is compatible with iOS 12.0 and later versions.

Integration

DriveKit SDK is available on Cocoapods master repo.
To access the framework in the repository, add the following lines to your Podfile:
Podfile
target 'my-target' do
pod 'DriveKitCore'
end

Project configuration

Even if your app does not use Bluetooth, since DriveKit imports CoreBluetooth framework, you must include Bluetooth usage description keys in your Info.plist file: NSBluetoothAlwaysUsageDescription (and NSBluetoothPeripheralUsageDescription if your deployment target is < iOS 13). This value can be localized (see our English file for example).
If you don't do this, your app will be rejected when you will send the binary to App Store Connect.

Add background fetch capability

Starting from DriveKit 1.36, the SDK periodically checks for changes related to the status of authorizations, sensors as well as user disconnection. This information is included in the diagnostic log file and shared with the DriveQuant platform.
To be more accurate, this feature needs to have background fetch capability and a task id declared:
  1. 1.
    Configure Capabilities:
    1. 1.
      Go to the "Signing & Capabilities" tab of your target settings.
    2. 2.
      Add "Background Modes" capability and enable "Background fetch".
  2. 2.
    Add background task id in your Info.plist file:
    1. 1.
      Go to the "Info" tab of your target settings.
    2. 2.
      Add “Permitted background task scheduler identifiers” (BGTaskSchedulerPermittedIdentifiers) array to the “Custom iOS Target Properties” and add com.drivequant.diagnosis.app.refresh in this array:
In the case you already have a background refresh task, as iOS allow only one scheduled background fetch task, you will need to reuse your existing BGAppRefreshTask to call the following function:
DKSDKDiagnosis.shared.enqueueDiagnosisOperation(source: .backgroundFetch) { success in
//task.setTaskCompleted(success: success)
}
In this case, don’t add the new “Permitted background task scheduler identifier” to your Info.plist.

Initialization

DriveKit initialization

To initialize DriveKit in your app, you must call the initialization method in didFinishLaunchingWithOptions method of your application class.
The initialization method optionally expects an implementation of DriveKitDelegate:
AppDelegate.swift
import DriveKitCoreModule
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
DriveKit.shared.initialize(delegate: self)
...
}
extension AppDelegate: DriveKitDelegate {
func driveKitDidConnect(_ driveKit: DriveKit) {
// Connected to DriveKit.
}
func driveKit(_ driveKit: DriveKit, didReceiveAuthenticationError error: RequestError) {
// DriveKit authentication error: \(error).
}
func driveKitDidDisconnect(_ driveKit: DriveKit) {
// Disconnected from DriveKit.
}
func userIdUpdateStatusChanged(status: UpdateUserIdStatus, userId: String?) {
// DriveKit userId updated: userId = \(userId), status = \(status).
}
func driveKit(_ driveKit: DriveKit, accountDeletionCompleted status: DeleteAccountStatus) {
// account deletion completed with status \(status).
}
}
All DriveKit modules have a method initialize that must be called in didFinishLaunchingWithOptions method of your AppDelegate file.

Add API key

To use DriveKit framework, you have to obtain an API Key from DriveQuant. If you don't have an API key, please contact DriveQuant.
Once your API key is securely stored in your application, you can configure DriveKit by calling the following method:
DriveKit.shared.setApiKey(key: "MyApiKey")

Identify user

Each driver must be identified with a unique identifier. Once you have this identifier, configure DriveKit by calling the following method:
DriveKit.shared.setUserId(userId: "MyUserId")
You can call these 2 configuration methods anywhere in your app code. DriveKit will save the value locally. If the app is killed and relaunched, DriveKit will be reconfigured automatically.
We recommend never using an email address or phone number to define the unique user ID. It is recommended that you set up a unique, universal and anonymous user ID. For example, you can generate a globally unique identifier (GUID) for each of your users.
DriveKit SDK will not work until you set the API key and the userId.

Check your configuration

You can check if DriveKit SDK is well configured with the following method:
DriveKit.shared.isConfigured()
This method returns true if it is well configured.

Reset

If you need to reset DriveKit configuration (user logout for example), you can call the following method:
DriveKit.shared.reset()
All data saved locally by DriveKit will be erased.
All DriverKit frameworks have reset method that erases all data saved locally by the framework.
Make sure that you call reset method of all frameworks to fully reset DriveKit configuration.

Logging

DriveKit comes with a logging feature that is enabled by default. This feature allows you to quickly identify the cause of a problem. We recommend leaving the log enabled as it does not consume memory space and is useful in the support phase. However, if you don't want to use it, it can be disabled.
Log will be written in app directory. One log file per month will be written with the name log-<YEAR>-<MONTH>.txt (example: log-2019-8.txt). All DriveKit modules log in this file. You can get a zip file with the log files of the previous month and the current one with the method DriveKitLog.shared.getZippedLogFilesUrl(), or by clicking on “Contact support” and changing the email receiver. The file will be in attachment of the email.
You can also make files of your application (including DriveKit log files) available in the iOS Files app by adding these 2 keys to your project's Info.plist file: UIFileSharingEnabled and LSSupportsOpeningDocumentsInPlace, setting them both to true.
To be able to access logs from Files app, you must add the following entries in your Info.plist file: UIFileSharingEnabled and LSSupportsOpeningDocumentsInPlace, setting both to true.
Disable logging by calling:
DriveKit.shared.disableLogging()
To activate logging, call the following method:
DriveKit.shared.enableLogging()

Listen for permissions and sensors status changes

If the user disables the sensors or revokes permissions, the application would not be able to detect and record a trip. To avoid this, the SDK identifies important sensor state and permission changes.
These events are shared and you can use them in your application to inform the user via a visual alert or by displaying a notification.
Event changes callbacks may not be fired in real time due to technical restrictions of iOS.

DKDeviceConfigurationDelegate

DKDeviceConfigurationDelegate is a protocol used to get callbacks when device configuration changes are detected.
protocol DKDeviceConfigurationDelegate: AnyObject {
func deviceConfigurationDidChange(event: DKDeviceConfigurationEvent)
}

Add a delegate

To add a delegate and listen for Device Configuration Events, you can call the following function
DriveKit.shared.addDeviceConfigurationDelegate(self)

Remove a delegate

To remove a specific delegate, call the following method:
DriveKit.shared.removeDeviceConfigurationDelegate(self)

Remove all delegates

To remove all delegates, call the following method:
DriveKit.shared.removeAllDeviceConfigurationDelegates()

DKDeviceConfigurationEvent

DKDeviceConfigurationEvent is a class describing a device configuration event.
class DKDeviceConfigurationEvent {
let type: DKDeviceConfigurationEventType
let isValid: Bool
}
Attribute
Type
Description
type
Enum
DKDeviceConfigurationEventType enum describing the type of event
isValid
Boolean
Boolean describing whether the device configuration event is valid or not

DKDeviceConfigurationEventType

public enum DKDeviceConfigurationEventType {
case activityPermission
case locationPermission
case bluetoothPermission
case notificationPermission
case lowPowerMode
case locationSensor
case bluetoothSensor
}
Possible types are:
Event type
Description
activityPermission
Motion & Fitness permission status changed
locationPermission
Location permission status changed
bluetoothPermission
Bluetooth permission status changed
notificationPermission
Notifications permission status changed
lowPowerMode
Low Power Mode status changed
locationSensor
Location sensor status changed
bluetoothSensor
Bluetooth sensor status changed
The DriveKit SDK will run optimally if the isValid value of each event is true. The table below explains the impact of a status that is not true.
Event
Criticality
Consequence if value is false
LocationPermission
🔴
No trip recording if app has no access to GPS sensor
BluetoothPermission
🟡
No trip detection based on Bluetooth system
ActivityPermission
🟡
Detected transportation mode mode can be inaccurate when no access to this permission
NotificationPermission
🟢
Your application cannot send notification to the user if the permission is revoked.
lowPowerMode
🟢
No considerable impact
LocationSensor
🔴
No trip recording if GPS sensor is disabled
BluetoothSensor
🟡
No trip detection based on Bluetooth system. Can also impact beacon trip detection.

Get user’s information

To get user’s information (first name, last name and pseudo), call the getUserInfo method. It will retrieve and save these data locally:
DriveKit.shared.getUserInfo(synchronizationType: .defaultSync) { status, userInfo in
if status == .success {
// Get user's names in userInfo object.
}
}

Update user’s information

You can add information to a user's account such as first name, last name and pseudo. These details are optional and you can choose to make the user's account anonymous. To update the user's information, you must call the updateUserInfo method:
DriveKit.shared.updateUserInfo(pseudo: "New_pseudo") { success in
if success {
// The pseudo has been successfully updated.
}
}
Or to update all information:
DriveKit.shared.updateUserInfo(firstname: "New_firstname", lastname: "New_lastname", pseudo: "New_pseudo") { success in
if success {
// The firstname, lastname and pseudo have been successfully updated.
}
}

Update UserId

It is possible to update the userId by calling the following method:
DriveKit.shared.updateUserId(userId: "newUserId")
To be able to check whenever userId got updated and catch the update status, you have to use DriveKitDelegate delegate.

Account deletion

You can delete a driver's account in DriveKit. This action deletes all the data related to the account.
The deletion can be done instantly or with delay.
  • In the first case, when the method is called, the account is instantly deleted.
  • In the second case, the driver has 30 days to log back into the application and reactivate his account.
To delete a driver's account, use the following method:
Swift
DriveKit.shared.deleteAccount(instantDeletion: false)
instantDeletion can have 2 values:
  • false : Default value, allows the user to recover the deleted account by logging-in again with the same credentials. Users have 30 days starting from the day when the account was deleted.
  • true : Allow to delete an account instantly. The account and all the related data will be immediately deleted and no rollback is possible.
Your team needs to have the deletion feature activated to use this method. Please contact DriveQuant if you need it.
To be able to check whenever the account deletion is complete, you have to use the DriveKitDelegate interface.
You should restore the DriveKit API key in the onAccountDeleted() callback only when the status value is SUCCESS.