# Services

**Shared Instance**

Use the shared instance as your interface to the MOVE SDK.

```swift
static let shared: MoveSDK
```

## **Detection Services**

### **Start Automatic Detection**

Starts the required detection services stated in the [MoveConfig](https://docs.movesdk.com/move-platform/sdk/models/moveconfig) passed on initialization. Starting the service will set the [MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate) to `.running`.

{% hint style="warning" %}
**Precondition**: SDK must be in`.ready`[MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate)
{% endhint %}

```swift
func startAutomaticDetection() -> Bool
```

Returns false if the SDK is not in `.ready` state.

### **Stop Automatic Detection**

Stops the automatic detection service, including all SDK services like driving detection, points of interest, walking and places. Stopping the service will set the [MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate) back to `.ready`.&#x20;

{% hint style="warning" %}
**Precondition**: SDK must be in`.running`[MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate).
{% endhint %}

```swift
func stopAutomaticDetection() -> Bool
```

Returns false if the SDK is not in `.ready` state.

### **Force Trip Recognition**

Temporarily calibrates the SDK to the highest detection mode.

In order to optimize battery consumption, the SDK goes through different detection modes with different battery consumption levels, depending on the user's current behavior and activity. In general, the SDK is responsible for alternating between those different detection modes.&#x20;

The SDK also provides hosting apps this API to call if they have their own reasons (like buttons, sensors or beacons) to believe that the user is starting a trip. This will make sure the SDK is on the highest detection state to detect the trip faster.

{% hint style="warning" %}
&#x20;**Precondition**: SDK must be in`.running` [MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate).
{% endhint %}

```swift
func forceTripRecognition()
```

### **Manual Start Trip**

Manually force the start of a trip, bypassing trip validation checks. This non-standard SDK usage may be feasible only in situations where active user input can be expected. Using the metadata parameter, self-defined information can be added to each trip which can be fetched from the [timeline](https://docs.movesdk.com/move-platform/backend/move-backend/move-timeline-api#trip-metadata).

```swift
func startTrip(metadata: [String: String] = [:]) -> Bool
```

Returns false if the SDK is not in `.ready` state.

{% hint style="warning" %}
**Precondition**: MOVE SDK must be in`READY`[MoveSdkState](https://docs.movesdk.com/move-platform/sdk/models/movestate).

Manually starting a trip bypasses additional trip detection checks. Manually started trips must be ended with [`finishCurrentTrip()`](#finish-current-trip)

It is recommended not to use [MoveOptions](https://docs.movesdk.com/move-platform/models/moveoptions#ios) `motionPermissionMandatory` or `backgroundLocationPermissionMandatory`with this API, as they will be ignored.
{% endhint %}

### **Finish Current Trip**

Ends the current ongoing trip.

This API will end the ongoing trip and set [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate) back to `.idle`. The SDK is responsible for detecting the trip start and end points. The SDK also provides hosting apps this API to call if they have their own reasons (like sensors or beacons) to believe that the user's trip has ended.

{% hint style="warning" %}
**Precondition**:[ MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate) should be in an active trip.
{% endhint %}

```swift
func finishCurrentTrip()
```

{% hint style="info" %}
If this API is called while the user is active on a driving trip, a new trip will start again right away. If the intention is to un-track the ongoing trip, call `ignoreCurrentTrip`API.

More information about trip states can be found in [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate).
{% endhint %}

{% hint style="info" %}
If the trip was started with [`startTrip(metadata:)`](#manual-start-trip) `finishCurrentTrip()` brings the SDK back to READY state.
{% endhint %}

### **Ignore Current Trip**

Ignores the current ongoing trip.&#x20;

This API will set the ongoing [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate) to `.ignored`. Data of ignored trips is purged and not sent to the server.

{% hint style="warning" %}
**Precondition**: [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate) should be in an active trip.
{% endhint %}

```swift
func ignoreCurrentTrip()
```

### **Set Trip Start Listener**&#x20;

Provides a block to be invoked when a trip actually begins.

In comparison to the tripStateListener (only state changes) the tripStartListener will provide you with the start time of the actual trip.

```swift
func setTripStartListener(_ listener: @escaping MoveTripStartCallback)
```

## Processing Services

### **Get SDK State**

Gets the current[ MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate).

```swift
func getSDKState() -> MoveSDKState
```

| **Return**                                                                  |                  |
| --------------------------------------------------------------------------- | ---------------- |
| [MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate) | Latest SDK State |

### **Set SDK State Listener**

Provide a block to be invoked every time [MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate) changes.

{% hint style="info" %}
Set the [MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate) listener before initializing the SDK to anticipate the SDK [State](https://docs.movesdk.com/move-platform/sdk/models/movestate) changes triggered by the initialization API. \
Here the host app can start the SDK services when [MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate) is`.ready.`
{% endhint %}

```swift
func setSDKStateListener(_ listener: SDKStateCallback)
```

| **Callback**                                                                                             |                                                                                                                                                                                                                                  |
| -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [SDKStateCallback](https://docs.movesdk.com/move-platform/models/listeners-callbacks#sdk-state-listener) | Block that gets invoked every time[ MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate) is changed and provides the updated [ MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate). |

### **Get Trip State**

&#x20;Gets the current [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate).

```swift
func getTripState() -> MoveTripState
```

| **Return**                                                                       |                                                                                          |
| -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate) | Current [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate) |

### **Set Trip State Listener**

Provide a block to be invoked every time [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate) changes.

```swift
func setTripStateListener(_ listener: TripStateCallback)
```

| Callback                                                                                                   |                                                                                                                                                                                                                                             |
| ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [TripStateCallback](https://docs.movesdk.com/move-platform/models/listeners-callbacks#trip-state-listener) | Block that gets invoked every time  [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate) is changed and provides the updated  [MoveTripState](https://docs.movesdk.com/move-platform/sdk/models/movetripstate). |

### Get Device Status

Gets the current [MoveDeviceStatus](https://docs.movesdk.com/move-platform/sdk/models/movedevicestatus)*.*

```swift
func getDeviceStatus() -> MoveDeviceStatus
```

| Return                                                                                 |                                                                                                |
| -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| [MoveDeviceStatus](https://docs.movesdk.com/move-platform/sdk/models/movedevicestatus) | Current [MoveDeviceStatus](https://docs.movesdk.com/move-platform/sdk/models/movedevicestatus) |

### Get Service Failures

Gets the current [MoveServiceFailures](https://docs.movesdk.com/move-platform/models/moveservicefailure#ios).

```swift
func getServiceFailures() -> [MoveServiceFailure]
```

| Return                                                                                             |                            |
| -------------------------------------------------------------------------------------------------- | -------------------------- |
| List of [MoveServiceFailure](https://docs.movesdk.com/move-platform/models/moveservicefailure#ios) | A list of failed services. |

### Set Service Failure Listener

```swift
func setServiceFailureListener(_ listener: @escaping MoveServiceFailureCallback)
```

Provide a block to be invoked every time [MoveServiceFailures ](https://docs.movesdk.com/move-platform/models/moveservicefailure#ios)change.

| Callback                                                                                              |                                                             |
| ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
| [MoveServiceFailureCallback](https://docs.movesdk.com/move-platform/models/listeners-callbacks#ios-6) | Block that gets invoked when service failure state changes. |

### Get Service Warnings

Gets the current [MoveServiceWarnings](https://docs.movesdk.com/move-platform/models/moveservicewarning#ios).

```swift
func getServiceWarnings() -> [MoveServiceWarning]
```

| Return                                                                                               |                                       |
| ---------------------------------------------------------------------------------------------------- | ------------------------------------- |
| List of [MoveServiceWarnings](https://docs.movesdk.com/move-platform/models/moveservicewarning#ios). | A list of partially working services. |

### Set Service Warning Listener

Provide a block to be invoked every time [MoveServiceWarnings ](https://docs.movesdk.com/move-platform/models/moveservicewarning#ios)change.

```swift
func setServiceWarningListener(_ listener: @escaping MoveServiceWarningCallback)
```

| Callback                                                                                              |                                                       |
| ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------- |
| [MoveServiceWarningCallback](https://docs.movesdk.com/move-platform/models/listeners-callbacks#ios-7) | Block that gets invoked when service warnings change. |

### **Set Metadata Listener**

Provide a block returning bundle of key-value pairs to be appended to the trip metadata before the trip finishes.

Host apps can use this API to add any app-level information (for ex. Bluetooth beacon detected, foreground/background time, etc) to append to a trip as metadata. This metadata will be forwarded back along with the trip when fetched by the client-server, so the host app can utilize it in its app. Note: The SDK will not use this metadata element in any way, it is just passed through to the project environment.

The block provides the trip's start and stop times. Make sure to only include metadata events that are relevant for the given start and end periods.

```swift
func setTripMetaDataListener(_ listener: MetaDataCallback)
```

| **Callback**                                                                                                 |                                                                                                   |
| ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- |
| [MetaDataCallback](https://docs.movesdk.com/move-platform/models/listeners-callbacks#trip-metadata-provider) | Block that gets invoked on every trip finish. The block provides the trip's start and stop times. |

**Usage Example**

```swift
MoveSDK.shared.setMetadataListener { (tripStartTime, tripEndTime) in
    getCollectedMetadataForPeriod(start: tripStartTime, end: tripEndTime)
}
```

### **Set Log Listener**

Provide a block to be invoked every time a new SDK log event occurs.

```swift
func setLogListener(_ listener: LogCallback)
```

### **Set Console Logging State** <a href="#set-log-listener" id="set-log-listener"></a>

Toggles console logging enabled state.

This doesn't affect recieving the logs via  `setLogListener(_ listener: MoveLogCallback)` API.

Enabled by default.

```swift
func setConsoleLogging(enabled: Bool) 
```

| **Parameter** |                                                          |
| ------------- | -------------------------------------------------------- |
| enabled       | Boolean that sets SDK console logging to enabled or not. |

### Set Health Score Listener

```swift
func setHealthScoreListener(_ listener: @escaping MoveHealthScoreCallback)
```

| **Parameter**                                                                                                    |                                                         |
| ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |
| [MoveHealthScoreCallback](https://docs.movesdk.com/move-platform/models/listeners-callbacks#sdk-health-listener) | Block that get's invoked when the health score changes. |

### Geocoding

Geo-coordinate address lookup.

```swift
func geocode(latitude: Double, longitude: Double, completion: @escaping (Result<String, MoveGeocodeError>) -> Void)
```

<table data-header-hidden><thead><tr><th width="177"></th><th></th></tr></thead><tbody><tr><td><strong>Parameter</strong></td><td></td></tr><tr><td>latitude</td><td>Geo-coordinate latitude</td></tr><tr><td>longitude</td><td>Geo-coordinate longitude</td></tr><tr><td>completion</td><td>Callback that returns a <em>Result</em> with an address S<em>tring</em> or a <a href="../../../models/movegeocodeerror#ios">MoveGeocodeError</a></td></tr></tbody></table>

Geocode will use Apple's builtin *CLGeocoder.reverseGeocodeLocation* or fallback to contacting the MOVE backend to attempt a geo-lookup.

{% hint style="warning" %}
**Throttle:** *Geocode* is limited to a maximum of 100 lookups per hour.

*CLGeocoder.reverseGeocodeLocation* has its own throttling and maybe used up for the app calling this function.
{% endhint %}

### **Delete Local Data**

Deletes all the collected user SDK data stored on the device. This doesn't affect the [MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate).

{% hint style="warning" %}
**Precondition:** [MoveSDKState](https://docs.movesdk.com/move-platform/sdk/models/movestate) should be initialized.
{% endhint %}

```swift
func deleteLocalData()
```

### **Synchronize User Data**

Used to force synchronizing user data with the SDK server. Limited to once per 2 minutes.

```swift
func synchronizeUserData()
```

Returns FALSE in case there are Timeline-relevant packages in the queue that remain to be sent to the SDK Backend; and it returns TRUE in case the queue is empty.

## Other Services

### Live Location TAG

{% hint style="info" %}
New feature since MOVE SDK 2.8.0
{% endhint %}

Adds a Tag (=string value) to trip events. This tag information is added to the timeline data.

To clear the Tag pass `null` as parameter.

After a `shutdown(...)` ([Android](https://docs.movesdk.com/move-platform/sdk/android/services#shutdown-sdk) / [iOS](#shutdown-sdk)) the tag is also cleared.

```swift
func setLiveLocationTag(_ tag: String?) -> Bool
```

<table data-header-hidden><thead><tr><th width="158"></th><th></th></tr></thead><tbody><tr><td><strong>Parameters</strong></td><td></td></tr><tr><td>tag</td><td>String <code>[a-z] [0-9]</code> and <code>null</code> to clear the Tag.</td></tr></tbody></table>

<table data-header-hidden><thead><tr><th width="160"></th><th></th></tr></thead><tbody><tr><td><strong>Return values</strong></td><td></td></tr><tr><td>true</td><td>Live Location Tag is applied.</td></tr><tr><td>true</td><td>Live Location Tag is cleared. (parameter <code>null</code>)</td></tr><tr><td>false</td><td>Live Location Tag exceeds the limit of 200 characters.</td></tr><tr><td>false</td><td>Live Location Tag is blank or empty.</td></tr><tr><td>false</td><td>If the passed chars are not one of these [a-z] [0-9].</td></tr></tbody></table>

### Initiate Assistance Call

*New feature in MOVE SDK 2.x; configuration in MOVE dashboard pending - please* [*get in touch*](mailto:info@dolph.in?subject=MOVE%20SDK)*.*

Initiate an assistance call to emergency services.

```swift
func initiateAssistanceCall(_ completionHandler: @escaping (MoveAssistanceCallStatus) -> Void)
```

| **Parameters**    |                                                                                                                                |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| completionHandler | A callback returning a [MoveAssistanceCallStatus](https://docs.movesdk.com/move-platform/models/moveassistancecallstatus#ios). |

The application should process the callback status and inform the user in case of failure.

{% hint style="warning" %}
**Precondition:** The assistance call service needs to be configured in the MOVE dashboard. The SDK needs to be in *ready* or *running* state.
{% endhint %}

### Set Assistance MetaData

*New feature in MOVE SDK 2.1*

```swift
func setAssistanceMetaData(_ metadata: String)
```

| **Parameters** |                                                         |
| -------------- | ------------------------------------------------------- |
| metadata       | A string to be sent with each assistance call or impact |

The metadata string is sent to the server with each manual assistance call and with each AID report. The contents of the string can be anything, e.g. JSON data. The assistance data is persisted once set.

### Get Device Qualifier

*New feature in MOVE SDK 2.2*

Get a unique qualifier to identify the individual device.

```swift
func getDeviceQualifier() -> String
```

The device qualifier should be passed to the backend during user registration. See [Move backend](https://docs.movesdk.com/move-platform/backend/move-backend/move-admin-api#gettingstartedwiththedolphinmovetimelineservice-authentication).

## Device Discovery

Device discovery for iBeacon and Audio devices. Multiple devices can be registered but limitations of `CLLocationManager` region API may apply.

From the start of a trip registered devices are scanned after a period `deviceDetectionDelay`, beacons are scanned for a duration `deviceDetectionDuration` repeated after an interval         `deviceDetectionInterval`, see [`MoveOptions`](https://docs.movesdk.com/move-platform/models/moveoptions#ios).

If  `stopScanOnFirstDiscovered` is set the scan stops after any device is discovered.

Device scanning results are appended to the trip metadata.

Registering/unregistering devices during a trip may result in undefined behavior.

### Register Device

Register an additional device:

```swift
func register(devices: [MoveDevice])
```

### Unregister Device

Unregister a device:

```swift
func unregister(devices: [MoveDevice])
```

{% hint style="info" %}
Since MOVE SDK v2.13: Devices are persisted after [shutdown](https://docs.movesdk.com/move-platform/sdk/api-interface/setup#shutdown).
{% endhint %}

### Get Registered Devices

Get current registered devices.

```swift
func getRegisteredDevices() -> [MoveDevice]
```

### **Set Device Discovery Listener**

Set a device discovery listener to be fired when registered [MoveDevice](https://docs.movesdk.com/move-platform/models/movedevice#ios)s are scanned. It returns a list of the devices registered with `register(devices: [MoveDevice])`. If the option [`stopScanOnFirstDiscovered`](https://docs.movesdk.com/move-platform/models/moveoptions/devicediscovery#ios) is set the list may be incomplete.

```swift
func setDeviceDiscoveryListener(_ listener: @escaping MoveDeviceDiscoveryCallback)
```

| **Callback**                                                                                           |                                                                           |
| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------- |
| [MoveDeviceDiscoveryCallback](https://docs.movesdk.com/move-platform/models/listeners-callbacks#ios-9) | Block that gets invoked whenever a scan for registered devices completes. |

### Set MoveDevice Connection State Listener

{% hint style="info" %}
Since MOVE SDK v2.10.0
{% endhint %}

Set a [MoveDevice](https://docs.movesdk.com/move-platform/sdk/models/movedevice) connection state listener to be fired when the connection state of a previously registered [MoveDevice](https://docs.movesdk.com/move-platform/models/movedevice#android) has changed. Only works with paired audio devices, not iBeacons.

```swift
func setDeviceStateListener(_ listener: @escaping MoveDeviceStateCallback)
```

| **Parameters**                                                                                      |                                                                                                                                         |
| --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| [MoveDeviceStateCallback](https://docs.movesdk.com/move-platform/models/listeners-callbacks#ios-13) | A callback returning the [MoveDevice](https://docs.movesdk.com/move-platform/sdk/models/movedevice) which connection state was changed. |

### **Set Remote Config Change Listener**&#x20;

{% hint style="info" %}
Since MOVE SDK v2.5
{% endhint %}

Provide a block to be invoked every time [MoveConfig](https://docs.movesdk.com/move-platform/models/moveconfig#ios) was successfully fetched from the server.

If the MoveConfig object couldn't be fetched from the server then a [MoveConfigurationError](https://docs.movesdk.com/move-platform/models/moveconfigurationerror#ios) ServiceUnreachable will be triggered.

```swift
func setRemoteConfigChangeListener(_ listener: @escaping MoveRemoteConfigChangeCallback)
```

| **Parameters** |                                                                           |
| -------------- | ------------------------------------------------------------------------- |
| listener       | A callback returning a MoveConfig object after a successful server fetch. |

### **Get Configuration**

Gets the current used Move configuration set in setup/update or configuration. If options flag `useBackendConfig` is set returns configuration set in dashboard.&#x20;

{% hint style="info" %}
Since MOVE SDK v2.16
{% endhint %}

```swift
func getMoveConfig() -> MoveConfig?
```

| **Return**                                                                 |                                                                                                        |
| -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| [MoveConfig](https://docs.movesdk.com/move-platform/sdk/models/moveconfig) | Move Configuration passed in setup/update or configuration from backend if *useBackendConfig* is set.. |

### **Step Counter (via HealthKit)**

{% hint style="info" %}
Since MOVE SDK v2.14
{% endhint %}

See section e[#health-permissions](https://docs.movesdk.com/move-platform/appendix/ios/permission-handling#health-permissions "mention") in Appendix.
