# Get started

## Prerequisite

Before starting DriveKit Driver Achievement integration, make sure that you have [initialized DriveKit](https://docs.drivequant.com/get-started-drivekit/ios), especially if you have [disable the SDK auto-initialization](https://docs.drivequant.com/get-started-drivekit/ios/advanced-configurations#manually-initialize-the-sdk)..

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

## Integration

### Get framework

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

## **Get Streaks**

To get Driver streaks, you have to call the following method:

```swift
public func getStreaks(type: SynchronizationType = .defaultSync, completionHandler: @escaping (StreakSyncStatus, [Streak]) -> ())
```

`SynchronizationType` can have 2 values:

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

`StreakSyncStatus` in the completionHandler can have 4 values:

1. `noError`: synchronization has been successfully performed.
2. `cacheDataOnly`: synchronizationType has been set to cache.
3. `failedToSyncStreakCacheOnly`: synchronization has failed, only streaks previously synchronized are returned.
4. `syncAlreadyInProgress`: a synchronization is in progress, only streaks previously synchronized are returned until the synchronization is finished.

### **Streak description**

| **Attribute** | **Type**       | **Description**         |
| ------------- | -------------- | ----------------------- |
| `theme`       | DKStreakTheme  | Streak Theme identifier |
| `current`     | DKStreakResult | Current streak result   |
| `best`        | DKStreakResult | Best streak result      |

#### Streak themes description

The themes and conditions to increment the sequences of the trip are the following:

* `phoneDistraction`: the driver has not handled his phone.
* `safety`: the safety score of the trip is higher or equal to 9.8.
* `speeding`: the speeding score of the trip is higher or equal to 9.8.
* `acceleration`: there wasn’t any harsh acceleration event during the trip.
* `brake`: there wasn’t any hard braking event during the trip.
* `adherence`: there wasn’t any adherence threshold crossing during the trip.
* `call`: the driver has not made forbidden call during the trip.

#### Streak Result description

| **Attribute** | **Type** | **Description**                                     |
| ------------- | -------- | --------------------------------------------------- |
| `distance`    | Double   | Total distance travelled during streak (in meters)  |
| `duration`    | Double   | Total duration travelled during streak (in seconds) |
| `tripNumber`  | Int      | Number of trips performed within streak             |
| `startDate`   | Date     | Date of the first trip of the streak                |
| `endDate`     | Date     | Date of the last trip of the streak                 |

## **Get Badges**

To get Driver badges, your have to call the following method:

```swift
public func getBadges(type: SynchronizationType = .defaultSync, completionHandler: @escaping (BadgeSyncStatus, [DKBadge], Int) -> ())
```

`SynchronizationType` can have 2 values:

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

`BadgeSyncStatus` in the completionHandler can have 4 values:

1. `noError`: Synchronization has been successfully performed.
2. `cacheDataOnly`: SynchronizationType has been set to cache.
3. `failedToSyncStreakCacheOnly`: Synchronization has failed, only badges previously synchronized are returned.
4. `syncAlreadyInProgress`: A synchronization is in progress, only badges previously synchronized are returned until the synchronization is finished.

### Get badge statistics

It can be practical to get some badge statistics, like how many badges have been won and how many remain to be acquired. To get these information, call the following method:

```swift
public func getBadgeStatistics() -> DKBadgeStatistics
```

#### DKBadgeStatistics

| Field     | Type | Description                           |
| --------- | ---- | ------------------------------------- |
| acquired  | Int  | Total badge acquired by the user      |
| remaining | Int  | The number of badges not yet obtained |
| total     | Int  | Total badge count                     |

### Badge description

#### DKBadge

| **Attribute**          | **Type**                  | **Description**        |
| ---------------------- | ------------------------- | ---------------------- |
| `theme`                | String                    | Badge theme identifier |
| `category`             | DKBadgeCategory           | Badge category         |
| `badgeCharacteristics` | \[DKBadgeCharacteristics] | Badge properties       |

#### **DKBadgeCharacteristics**

| **Attribute**      | **Type** | **Description**                                       |
| ------------------ | -------- | ----------------------------------------------------- |
| `level`            | DKLevel  | Badge level                                           |
| `name`             | String   | Badge name                                            |
| `icon`             | String   | Badge icon name (for a won badge)                     |
| `defaultIcon`      | String   | Badge default icon name (for a pending badge)         |
| `descriptionValue` | String   | Badge goal description                                |
| `progress`         | String   | Badge progress message                                |
| `progressValue`    | Double   | Distance or number of trips performed                 |
| `congrats`         | String   | Badge congratulations message                         |
| `threshold`        | Int      | Distance or number of trips required to win the badge |

#### **DKLevel**

* `.bronze`
* `.silver`
* `.gold`

#### **DKBadgeCategory**

* `.generic`
* `.ecodriving`
* `.safety`
* `.phoneDistraction`

## Get ranking

To get driver’s Ranking, you need to call the following method of `DriveKitDriverAchievement` class:

```swift
func getRanking(rankingType: DKRankingType,
                rankingPeriod: DKRankingPeriod = .weekly,
                rankingDepth: Int = 5,
                groupName: String = "All",
                type: SynchronizationType = .defaultSync,
                completionHandler : @escaping (RankingSyncStatus, DKRanking?) -> ())
```

### Ranking parameters

| **Attribute**   | **Type**            | **Description**                                                                                                                                                                                                                                                                                                                                          |
| --------------- | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `rankingType`   | DKRankingType       | Theme of the ranking.                                                                                                                                                                                                                                                                                                                                    |
| `rankingPeriod` | DKRankingPeriod     | Period of the ranking.                                                                                                                                                                                                                                                                                                                                   |
| `rankingDepth`  | Int                 | <p>This integer value must be between 5 and 20.</p><p>If you set this value to 5, the leaderboard will display: </p><ul><li>the top 5 users in the ranking</li><li>the position of the connected user</li><li>the positions of the 5 best neighbors of the connected user</li><li>the positions of the 5 worst neighbors of the connected user</li></ul> |
| `type`          | SynchronizationType | Whether data are fetch locally or from server.                                                                                                                                                                                                                                                                                                           |

#### **DKRankingType**

The DKRankingType enum values are:

* `safety,`&#x20;
* `ecoDriving,`&#x20;
* `distraction,`
* `speeding.`

#### **DKRankingPeriod**

The `DKRankingPeriod` enum values are:

* `weekly`: In the case of a weekly classification, the trips considered for the calculation of the user's position are those made between Monday midnight and Sunday midnight. If the user has not driven during the week, he is not ranked.
* `monthly`: In the case of a monthly ranking, the trips considered for the calculation of the user's position are those made between the first and last day of the month.. If the user has not driven during this period, he is not ranked.
* `allTime`: This ranking takes into account all of the driver's trips.

#### **RankingSyncStatus**

`RankingSyncStatus` in the callback can have 5 values:

1. `noError`: Synchronization has been successfully performed.
2. `cacheDataOnly`: SynchronizationType has been set to cache.
3. `failedToSyncRanking`: Synchronization has failed, only rankings previously synchronized are returned.
4. `syncAlreadyInProgress`: A synchronization is in progress, only rankings previously synchronized are returned until the synchronization is finished.
5. `userNotRanked`: The user is not ranked.

### **DKRanking Description**

| **Attribute**          | **Type**          | **Description**                                  |
| ---------------------- | ----------------- | ------------------------------------------------ |
| `rankingType`          | DKRankingType     | Theme of the ranking                             |
| `rankingPeriod`        | DKRankingPeriod   | Period of the ranking                            |
| `userPosition`         | Int               | Position of the driver in the driversRanked list |
| `userPreviousPosition` | Int?              | Previous position of the driver in the ranking   |
| `driversRanked`        | \[DKDriverRanked] | List of the rated drivers                        |
| `nbDriverRanked`       | Int               | Total number of rated drivers                    |

### **DKDriverRanked Description**

| **Attribute** | **Type** | **Description**                                                                                                                                                                                                         |
| ------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `userId`      | String?  | Unique identifier of the driver                                                                                                                                                                                         |
| `nickname`    | String?  | Driver’s nickname                                                                                                                                                                                                       |
| `rank`        | Int      | <p>Driver’s rank in the ranking.</p><p>This value is determined from the rounded score (to 2 decimal places). If two drivers have the same score, the one with the highest distance is considered as the first one.</p> |
| `score`       | Double   | <p>Driver’s score (according to the theme). </p><p>It corresponds to the average of all trip scores made during the specified period.</p>                                                                               |
| `distance`    | Double   | Covered distance by the driver in the specified period                                                                                                                                                                  |

### **Ranking access conditions**

To enter a ranking, a driver must fulfill the following requirements:&#x20;

* Weekly ranking: 2 trips and 10 km since the first day of the week;&#x20;
* Monthly ranking: 5 trips and 20 km since the first day of the month;&#x20;
* Permanent ranking: 10 trips and 50 km since his first trip.

### **Data update**

The scores, distances and ranks are updated every hour.
