# Get started

## Prerequisite

Before starting DriveKit Driver Data integration, make sure that you have [initialized DriveKit](https://docs.drivequant.com/get-started-drivekit/ios).

{% hint style="danger" %}
If you use Driver Data without having initialized DriveKit, the SDK may not work properly in your application.
{% endhint %}

## Integration

### Get framework

To add the DriverData module to your app using **Swift Package Manager,** add `DriveKitDriverData` from repository: `https://github.com/DriveQuantPublic/drivekit-sdk-spm.git` as dependency.

## Initialization

If you have [disabled the SDK auto-initialization](https://docs.drivequant.com/get-started-drivekit/ios/advanced-configurations#manually-initialize-the-sdk), an initialization phase is required to use the feature included in the Driver Data module. In the application's AppDelegate file, import `DriveKitDriverData:`

```swift
import DriveKitDriverDataModule
```

Then, to initialize Driver Data module in your app, you must call the initialization method in `didFinishLaunchingWithOptions` method of your AppDelegate file.

{% tabs %}
{% tab title="AppDelegate.swift" %}

```swift
import DriveKitCoreModule
import DriveKitTripAnalysisModule

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    DriveKit.shared.initialize()
    DriveKitDriverData.shared.initialize()
    ...    
}
```

{% endtab %}
{% endtabs %}

## Get driver trips

To get [Driver trips](https://docs.drivequant.com/trip-analysis/ios/references#trip), you have to call the following method:

```swift
public func getTripsOrderByDateDesc(type: SynchronizationType = .defaultSync, completionHandler: @escaping (TripSyncStatus, [DKTrip]) -> ())
```

`SynchronizationType` can have 2 values:

* `defaultSync`: if this value is used, the SDK will try to synchronize local trips with DriveQuant backend to get new trips or modified trips, and then return the trip list via the completionHandler.
* `cache`: if this value is used, no synchronization will be performed and only trips previously synchronized will be returned via the completionHandler.

`TripSyncStatus` in the completionHandler can have 4 values:

* `noError`: Synchronization has been successfully performed.
* `cacheDataOnly`: SynchronizationType has been set to `cache`.
* `failedToSyncTripsCacheOnly`: Synchronization has failed, only trips previously synchronized are returned.
* `syncAlreadyInProgress`: A synchronization is in progress, only trips previously synchronized are returned until the synchronization is finished.

The second argument in the `completionHandler` is the list of [DKTrip](https://docs.drivequant.com/trip-analysis/ios/references#trip) objects.&#x20;

{% hint style="info" %}
Trips are returned and sorted by end date in descending order.
{% endhint %}

{% hint style="warning" %}
If train trips have been recorded by Trip Analysis SDK, they won't be returned by this method.
{% endhint %}

Example:

```swift
DriveKitDriverData.shared.getTripsOrderByDateDesc(completionHandler: { status, trips in
    // Check status and use trips data
})
```

## Get specific trip

To get a specific [trip](https://docs.drivequant.com/trip-analysis/ios/references#trip), you have to call the following method:

```swift
public func getTrip(itinId: String, completionHandler: @escaping (TripSyncStatus, DKTrip?) -> ())
```

The `itinId` parameter is the unique identifier for a trip.

When you call this method, you will get trip data and trip safety events. If safety events are not synchronized locally for the trip, a synchronization with DriveQuant backend will be performed and then, the trip will be returned with safety events synchronized.

`TripSyncStatus` can have the same value as [above](#get-driver-trips) and the value `failedToSyncSafetyEvents` if the safety events synchronization failed.

The second argument in the `completionHandler` is the requested [Trip](https://docs.drivequant.com/trip-analysis/ios/references#trip) object, if exists.&#x20;

Example:

```swift
DriveKitDriverData.shared.getTrip(itinId: itinId, completionHandler: { status, trip in
    // Check status and use trip data
})
```

## Get trip road data

To get road data of the trip (latitude, longitude), you have to call the following method:

```swift
public func getRoute(itinId: String, completionHandler: @escaping (DKRoute?) -> ())
```

If `route` value in completionHandler is `nil` , the synchronization has failed.

Example:

```swift
DriveKitDriverData.shared.getRoute(itinId: itinId, completionHandler: { route in
    if let route = route {
        // Use route data
     } else {
        // Failed to synchronize route
     }
})
```

## Delete a trip

To delete a trip, you have to call the following method:

```swift
 public func deleteTrip(itinId: String, completionHandler: @escaping (Bool) -> ())
```

The `itinId` parameter is the unique identifier for a trip.

Example:

```swift
DriveKitDriverData.shared.deleteTrip(itinId: self.viewModel.itinId, completionHandler: { deleteSuccessful in
    if deleteSuccessful {
        // trip successfully deleted
    } else {
        // Failed to delete trip
    }
})
```

## Declare a trip made as passenger

When a trip is analyzed and the detected transportation mode is car, truck, or motorcycle, it is by default attributed to the driver. However, in some cases, the data may come from a passenger's smartphone.

\
In such cases, it is possible to indicate that the analyzed trip was recorded by an occupant of the vehicle who was not the driver.\
This section describes the method used to declare a trip as having been made as a passenger.

\
With this method, you can add a feature to your application that allows the user to declare that they were not the driver of the vehicle.

{% hint style="warning" %}
When a user declares that a trip was made as a passenger, it will **not** modify any scores related to the trip.
{% endhint %}

To declare a trip as a passenger with a comment, call the following code:

{% tabs %}
{% tab title="Swift" %}

```swift
let itinid = "myItineraryId"
let mode = DKDriverPassengerMode.passenger
let comment = "I was the passenger"
DriveKitDriverData.shared.updateDriverPassengerMode(itinId: itinid, mode: mode, comment: comment) { status in
	switch status {
	case .success:
    	// Success, the data have been updated in the local database
	case .userNotConnected:
    	// An error occurred, the user is not yet connected.
	case .invalidTransportationMode:
    	// Error, the trip was made with an alternative transport
	case .invalidItineraryId:
    	// Error, the provided itinerary identifier does not exist or has not been made by the user
	case .commentTooLong:
    	// Error, the comment is too long
	case .failedToUpdateMode:
    	// An error occurred, for example when the user has no network.
	}
}

```

{% endtab %}
{% endtabs %}

The method takes the following parameters:

| Field   | Type                  | Description                                         |
| ------- | --------------------- | --------------------------------------------------- |
| itinId  | String                | Unique trip identifier                              |
| mode    | DKDriverPassengerMode | Possible value: `driver` or `passenger`.            |
| comment | String                | The user can add a comment of up to 120 characters. |

The method returns a `UpdateDriverPassengerModeStatus` enum with the possible values:

<table><thead><tr><th width="316">Value</th><th>Description</th></tr></thead><tbody><tr><td>success</td><td>The passenger status has been successfully updated and local trip data is also updated.</td></tr><tr><td>userNotConnected</td><td>The user is not yet connected to DriveKit.</td></tr><tr><td>invalidItineraryId</td><td>The itinerary identifier does not exist.<br>Update is not taken into account and local trip data is not updated either.</td></tr><tr><td>invalidTransportationMode</td><td>The trip was made with alternative transport.<br>Update is not taken into account and local trip data is not updated either.</td></tr><tr><td>commentTooLong</td><td>The comment exceeds 120 characters.<br>Update is not taken into account and local trip data is not updated either.</td></tr><tr><td>failedToUpdateMode</td><td>An error has occurred, for example if the user has no network.<br>Update is not taken into account and local trip data is not updated either.</td></tr></tbody></table>

## **Get driver synthesis**

To get driver synthesis data, you have to call the following method:

```swift
public func getSynthesis(type: SynchronizationType = .cache, completionHandler: @escaping (SynthesisSyncStatus, DKSynthesis?) -> ())
```

`SynchronizationType` can have 2 values:

* `defaultSync`: if this value is used, the SDK will try to synchronize the driver synthesis data with DriveQuant backend and then return it via the completionHandler.
* `cache`: if this value is used, no synchronization will be performed and the data retrieved during the last synchronisation will be returned via the completionHandler.

`SynthesisSyncStatus` in the completionHandler can take 3 values:

* `cacheDataOnly`: SynchronizationType has been set to cache.
* `noError`: Synchronization has been successfully performed.
* `failedToSyncSynthesisCacheOnly`: Synchronization has failed, only data retrieved during the last synchronisation is returned.

Example:

```swift
import DriveKitDriverDataModule

DriveKitDriverData.shared.getSynthesis(type: .defaultSync) { status, synthesis in
    // Check status and use synthesis
}
```

```swift
public func getDriverTimelines(periods: [DKPeriod], type: SynchronizationType = .defaultSync, completionHandler: @escaping (TimelineSyncStatus, [DKDriverTimeline]?) -> Void)
```

`periods` attribute contains periods you are interested in: `.week` , `.month` and/or `.year`.

* `defaultSync`: if this value is used, the SDK will try to synchronize timelines with DriveQuant backend and then return them via the completionHandler.
* `cache`: if this value is used, no synchronization will be performed and the data retrieved during the last synchronisation will be returned via the completionHandler.
* `cacheDataOnly`: SynchronizationType has been set to cache.
* `noError`: Synchronization has been successfully performed.
* `failedToSyncTimelineCacheOnly`: Synchronization has failed, only data retrieved during the last synchronisation are returned.
* `noTimelineYet`: Synchronization has been successfully performed and there is currently no timeline.

```swift
import DriveKitDriverDataModule

DriveKitDriverData.shared.getTimelines(periods: [.week, .month], type: .defaultSync) { (status, timelines) in
    // Check status and use timelines
}
```

## Get **driver timelines**

To get driver timelines, you have to call the following method:

```swift
public func getDriverTimelines(
    periods: [DKPeriod],
    ignoreItemsWithoutTripScored: Bool = false,
    type: SynchronizationType = .defaultSync,
    completionHandler: @escaping (TimelineSyncStatus, [DKDriverTimeline]?) -> Void
)
```

`TimelineSyncStatus` in the `completionHandler` can take 4 values:

* `cacheDataOnly`: `SynchronizationType` has been set to cache.
* `noError`: Synchronisation has been successfully performed.
* `failedToSyncTimelineCacheOnly`: Synchronisation has failed, only data retrieved during the last synchronisation are returned.
* `noTimelineYet`: Synchronisation has been successfully performed and there is currently no timeline.

The second argument in the `completionHandler` is a list of [DKDriverTimeline](https://docs.drivequant.com/driver-data/references#dkdrivertimeline) object, one per period requested.&#x20;

Example:

```swift
import DriveKitDriverDataModule

DriveKitDriverData.shared.getDriverTimelines(periods: [.week, .month, .year], type: .defaultSync) { (status, timelines) in
    // Check status and use timelines
}
```

## Get driver profile

To get driver profile, you have to call the following method:

```swift
public func getDriverProfile(
   type: SynchronizationType = .defaultSync,
   completionHandler: @escaping (DKDriverProfileStatus, DKDriverProfile?) -> Void
)
```

`SynchronizationType` can have 2 values:

* `defaultSync`: if this value is used, the SDK will try to synchronize the driver profile with DriveQuant backend and then return it via the completionHandler.
* `cache`: if this value is used, no synchronisation will be performed and the data retrieved during the last synchronisation will be returned via the completionHandler.

`DKDriverProfileStatus` in the completionHandler can take 4 values:

* `success`: Synchronization type has been successfully performed.
* `failedToSyncDriverProfileCacheOnly`: Synchronisation has failed, only data retrieved during the last synchronisation is returned.
* `noDriverProfileYet`: Synchronisation has been successfully performed and there is currently no driver profile for this user.
* `forbiddenAccess`: Your team doesn’t have access to this data.

The second argument in the completionHandler is the [`DKDriverProfile`](https://docs.drivequant.com/driver-data/references#dkdriverprofile) object requested.

```swift
import DriveKitDriverDataModule

DriveKitDriverData.shared.getDriverProfile(type: .defaultSync) { (status, driverProfile) in
    // Check status and use driverProfile
}
```
