Interacting with Kruzr SDK

In this section we discuss some specific and frequently used methods which is relevant for any driving app. These methods help you interact with our Kruzr 360 Platform, helping you improve user experience and also build new features on top of them.

Broadly, we will cover 3 key points which involve such interactions:

  1. Trip Controls with manual override options for your users

  2. Trip List and Current Trip Detail access from our cloud to your app - using which you can create engaging illustrations and driver engagement programs

  3. Data Sync Preference which help you control WIFI or WIFI + Cellular Data syncs for trip files on your app.

Location and Activity permissions are most important aspect of any driving app. It ensures that app is able to automatically detect user trips, score them properly and ensure that data quality is reliable. Therefore, for promised quality of service you need to make absolutely sure that your users have provided the required permissions.

Get Registered Driver Details

Call getRegisteredDriver method with the following parameter to get information about the registered driver passed at the time of registration along with their total trip count, total drive time (in Seconds), total distance travelled (in KM) and average driving score.

TripManager.sharedInstance.getRegisteredDriver() { status, data, error in
    if error != nil {
        print(error)
        return
    }
    if let data = data {
        print(data) //dataType RegisteredDriver
    } else {
        print([])
    }
}
class RegisteredDriver {
    String companyName;
    String countryCode;
    String driverID;
    String email;
    String name;
    String phoneNumber;
    
    Double averageTripScore;
    Double totalDistanceTravelled;
    Int totalTripCount;
    Double totalTripDurationInSeconds;
}

Checking if user is registered or not

You can call this method to know if a user is registerd in the SDK or now. If false, you will have to register a user first first before calling any other SDK methods

TripManager.sharedInstance.isRegistered()

Clearing user details from the SDK

You can call this method to remove the user details from the SDK.

TripManager.sharedInstance.deRegisterUser()

Start Trip Manually

Manual Start Trip method is a useful way to provide your users with control over starting the trip themselves if they prefer it over Automatic Trip Detection. It also helps you make your app more complete in terms of possible user flows.

You can provide extra trip details through extraKeys in the form of Dictionary so that additional information can be provided to Kruzr platform for analytics and reporting purposes.

TripManager.sharedInstance.tripOn(isCopassanger: false, tripStartedMode: TripStartMode.manual, extraKeys: [:]) { (status,message) in
      if(status == 200){
          // Trip Started
      }else {
          // Unable to start trip
      }
}

Stop Trip Manually

Allows the user to manually end an ongoing trip. Please note that the trip may be automatically started or manually started - in either of the cases, an on-going trip can be terminated/stopped using this method.

TripManager.sharedInstance.tripEnd(isCopassanger: false,endCause: "MANUAL_TRIP_END")

Get Trip List

Trip list provides your app a method to fetch all the trips for a particular user within your app.

Please call fetchTripList method with the following parameters -

  • offset - the starting point/reference from which you need to fetch trips.

  • limit - how many trips you want to be fetched

TripManager.sharedInstance.getAllTrips(limit: limit, offset: offset) { status, data, error in
    if error != nil {
        print(error)
        return
    }
    if let data = data {
        print(data) //dataType [SingleTripResponseModel]
    } else {
        print([])
    }
}

It is recommended as to use combination of limit and offset while loading trip lists for users in your app. It will help you reduce the need making bulk downloads of all trips, specially in cases where number of trips for the user is very high. So, for example, if you want to fetch 12 trips between position 30 and 42, you will set offset as 30 and limit as 12.

Get Details of Completed Trip

Please call getTripDetail method with the following parameters to get details for a completed trip. You can use this information to generate trip summary pages and illustrations on historical/completed trips of users.

  • APP_TRIP_ID - TripID of the trip you want to fetch details for

TripManager.sharedInstance.getTripDetail(tripID: appTripId){ status, data, error in
    if error != nil {
        print(error)
        return
    }
    
    if let data = data {
        print(data) //dataType SingleTripResponseModel
    } else {
        print(nil)
    }
}

Get Trip Stats of Completed Trip

Please call getTripStats method with the following parameters to get trip stats for a completed trip. You can use this information to generate trip summary pages of users.

  • APP_TRIP_ID - TripID of the trip you want to fetch details for

TripManager.sharedInstance.getTripStats(tripID: appTripId){ status, data, error in
    if error != nil {
        print(error)
        return
    }
    
    if let data = data {
        print(data) //dataType TripStats
    } else {
        print(nil)
    }
}

Trip Stats

{
 extraTripScores : {
 hardAcceleration :: double,
 hardBraking :: double,
 hardTurn :: double,
 speeding :: double,
 drowsy :: double,
 hardAccelerationStarRating :: int,
 hardBrakingStarRating :: int,
 hardTurnStarRating :: int,
 speedingStarRating :: int,
 drowsyStarRating :: int,
 
}

Mark trip as Co-Passenger.

Use this method to update your recorded trip and designate it as a co-passenger trip. This functionality is particularly useful when you need to distinguish auto-detected trips in which you were not the driver.

TripManager.sharedInstance.wasCoPassengerInTrip(tripID: appTripId){ status, data, error in
    if error != nil {
        print(error)
        return
    }
    
    if let data = data {
        print(data) //dataType boolean
    } else {
        print(nil)
    }
}

Parameters:

  • "APP_TRIP_ID": The unique identifier of the trip you want to mark as a co-passenger trip.


Setting Preference for Trip Data Sync

You can define the preferences/settings if you would like to sync trip data of your users via WiFi ONLY or both, WiFi + Mobile Data. These implementations help you provide flexibility to your users on their data consumption and can be customized based on use case requirements. You can also use these on "App Settings" page to your users so that they can decide which sync method they want to set.

Please call dataShouldTransferOverWifi method with the following parameters:

  1. for useWIFIOnly pass true if you want data to sync just using wifi, or false if you want file upload to be on both mobile data and wifi.

TripManager.sharedInstance.dataShouldTransferOverWifi(shouldTransfer: useWIFIOnly)

Getting Current Data Sync Preference

As a business or product analysis requirement, you may need to classify/keep track of the current data sync setting a user has provided your app with - specially if you have implemented dataShouldTransferOverWifi as a user controlled setting within your app.

Please call shouldDataTransferOverWifiOnly method to get this value. This method will return the current data sync preference, which will be either true for data sync only on WIFI or false for data sync over WIFI or CELLULAR data.

TripManager.sharedInstance.shouldDataTransferOverWifiOnly()

Leaderboard Details

Call getLeaderboardUsers method with the following parameters to get details of the leaderboard.

Suppose you want to fetch users on the leaderboard with rank from position 16 to 25. Then offset will be 16 and limit will be 25-16 = 9.

  • limit - how many users to fetch

  • offset - from which position should users be fetched

TripManager.sharedInstance.getLeaderboardUsers(limit: limit, offset: offset) { status, data, error in
    if error != nil {
        print(error)
        return
    }
    if let data = data {
        print(data) //dataType [LeaderboardUser]
    } else {
        print([])
    }
}

LeaderboardUser object

LeaderboardUser {
    int rank;
    String username;
    Float averageTripScore;
    int totalTripCount;
}

Ranking details of current user

Call getUserRank method with the following parameter to get ranking details of the current user.

TripManager.sharedInstance.getUserRank() { status, data, error in
    if error != nil {
        print(error)
        return
    }
    if let data = data {
        print(data) //dataType UserRankingDetails
    } else {
        print([])
    }
}

You will get the registered drivers rank details in the following format.

UserRankingDetails {
    String currentRank;
    String percentile;
    Double averageTripScore;
    Int totalCount;
}

Metrics Data

This section contains the methods to get aggregated data for a particular period of date ranges.

You might need to use the dates in few of the API's. Here is an example to create a date of format 3 December 2023. Our methods assumes the date to be in UTC, so make sure to do the necessary conversion at your end.

var components = DateComponents()
components.year = 2023
components.month = 12
components.day = 3
components.hour = 0
components.minute = 0
components.second = 0
components.timeZone = TimeZone(abbreviation: "UTC")
// Create a calendar instance
let calendar = Calendar(identifier: .gregorian)
guard let date = calendar.date(from: components) else {
    return
}
print(date)

You will be getting most of the aggregation methods response in KruzrHistoricDoubleDataResponse

KruzrHistoricData {
    Double? data: 
    String startDate: String
    String endDate: 
}
KruzrHistoricDoubleDataResponse{
    Double? data: 
    [KruzrHistoricData] historicData:
}

Get Aggregated Driving Score for a particular duration

Call getAggregatedDrivingScore method with the following parameter to get the average driving score of the registered driver.

TripManager
    .sharedInstance
    .getAggregatedDrivingScore(startDate: String, endDate: String, periodicalType: MetrixPeriodicalType) { status, historicDoubleDataResponse, error in
        if error != nil {
            print(error)
            return
        }
        if let historicDoubleDataResponse = historicDoubleDataResponse {
            print(historicDoubleDataResponse) //dataType KruzrHistoricDoubleDataResponse

        } else {
            print([])
        }
    }        

Get Aggregated Driving Distance for a particular duration

Call getAggregatedDistanceTravelled method with the following parameter to get the distance driven in KM by the current registered driver.

TripManager
    .sharedInstance
    .getAggregatedDistanceTravelled(startDate: String, endDate: String, periodicalType: MetrixPeriodicalType) { status, historicDoubleDataResponse, error in
        if error != nil {
            print(error)
            return
        }
        if let historicDoubleDataResponse = historicDoubleDataResponse {
            print(historicDoubleDataResponse) //dataType KruzrHistoricDoubleDataResponse

        } else {
            print([])
        }
    } 

Get Aggregated Driving Time in seconds for a particular duration

Call getAggregatedDriveTimeInSeconds method with the following parameter to get duration driven in seconds by the current registered driver.

TripManager
    .sharedInstance
     .getAggregatedDriveTimeInSeconds(startDate: String, endDate: String, periodicalType: MetrixPeriodicalType) { status, historicDoubleDataResponse, error in
        if error != nil {
            print(error)
            return
        }
        if let historicDoubleDataResponse = historicDoubleDataResponse {
            print(historicDoubleDataResponse) //dataType KruzrHistoricDoubleDataResponse

        } else {
            print([])
        }
    } 

Get Aggregated Driving Score for a particular duration

Call getAggregatedDrivingBehaviourScore method with the following parameter to get individual driving behaviour score of the current registered driver.

TripManager.sharedInstance.getAggregatedDrivingBehaviourScore(startDate: startDate, endDate: endDate, periodicalType: MetrixPeriodicalType) { status, data, error in
    if error != nil {
        print(error)
        return
    }
    if let data = data {
        print(data) //dataType DrivingBehaviourScore
    } else {
        print([])
    }
}

You will get the response in the following format.

Currently this method is still under maintenance. We will return null for the respective score if we are unable to fetch that parameter. We will soon be adding the error message in the onFailure callback.

class DrivingBehaviourScore {
    Double hardAcceleration;
    [KruzrHistoricData] historicHardAcceleration;
    Double speeding;
    [KruzrHistoricData] historicSpeeding
    Double braking;
    [KruzrHistoricData] historicBraking
    Double laneChange;
    [KruzrHistoricData] historicLaneChange
    Double hardTurn;
    [KruzrHistoricData] historicHardTurn
    Double fatigue;
    [KruzrHistoricData] historicFatigue
}

Get Driving Summary for a particular duration

Call getDrivingSummary method with the following parameter to get individual driving summary of the current registered driver.

TripManager.sharedInstance.getDrivingSummary(startDate: startDate, endDate: endDate) { status, data, error in
    if error != nil {
        print(error)
        return
    }
    if let data = data {
        print(data) //dataType DrivingSummary
    } else {
        print([])
    }
}

You will get the response in the following format.

class DrivingSummary {
    Double distance;
    Int trips;
    Double duration;
    Double safetyScore;
    Double hardAcceleration;
    Double speeding;
    Double braking;
    Double laneChange;
    Double hardTurn;
    Double fatigue;
}

Working with vehicle tracking using MAC Address of the vehicle's bluetooth device

You might want to know whether the user is taking their trips in a particular vehicle (whether his own or the one assigned to him). Then you will need to pass the MAC address of the vehicle's bluetooth system to the Kruzr SDK. Then, whenever a trip is ongoing, the SDK will check whether the user is actually in that particular vehicle.

Saved details of the vehicle will be cleared when deRegister(logout) method is called. You will have to save the mac address again.

Saving, Fetching and Clearing vehicle's details

You can save a NearByDevices received in the scan methods as vehicle device through this method

TripManager.sharedInstance.saveVehicleDevice(nearByDevices: NearByDevices);

You can get the vehicle device (in String format) of the vehicle through this method.

TripManager.sharedInstance.getVehicleDevice();

You can clear the saved mac address of vehicle through this method

TripManager.sharedInstance.clearVehicleDevice();

Saving, Fetching and Clearing vehicle's MAC address

You can save a MAC address as the MAC address of vehicle through this method

Saved MAC address of the vehicle will be cleared when deRegister(logout) method is called. You will have to save the mac address again.

TripManager.sharedInstance.saveMacAddressOfVehicle(macAddress: vehicleMacAddress);

You can get the saved mac address (in String format) of the vehicle through this method.

TripManager.sharedInstance.getMacAddressOfVehicle();

You can clear the saved mac address of vehicle through this method

TripManager.sharedInstance.clearMacAddressVehicle();

Scanning for Nearby Bluetooth Devices

You can call this method to get nearby devices. Once the scanning starts onScanningStarted will be called followed by multiple callbacks of deviceFound on every new device discovery. Once the scanning ends, you will receive a callback in onScanningFinished. Usually the scanning stays active for 12 seconds as per default os rules.

Some Bluetooth devices, particularly low-energy (BLE) devices, may not advertise their name in their scan response. This means that the device's name is not available to discoverable apps.

do {
    try TripManager.sharedInstance.scanForNearbyDevices(kruzrNearbyDeviceScanDelegate: self )
} catch  {
    print(error)
}

If you are using self, you will also need to inherit KruzrNearbyDeviceScanDelegate to you swift class from which you will calling scan method. You will also need to implement these methods in your class.

func onScanningStarted() { 
    print("Scanning Started")
}
func deviceFound(device: CBPeripheral) {
    print("====== Device Found")
    print("identifier \(device.identifier)")
    print("and name " + (device.name ?? "N/A"))
    print("======")
}

func onScanningFinished() {
    print("Scanning Finished")
}

func requestUserToSwitchOnBluetooth() {
    print("requestUserToSwitchOnBluetooth")
}

func permissionsNotGranted() {
    print("permissionsNotGranted")
}

func deviceNotSupported() {
    print("deviceNotSupported")
}

You will to import CoreBluetooth to use CBPeripheral

Last updated

Was this helpful?