---
title: Samples
---


## Overview

Sahha provides your app with realtime data samples directly from Apple Health and Google Health Connect.

Samples are an array of events and values that occur within a time period that you specify.

For example:

- a `steps` sample which includes step count
- a `heartRate` sample which includes beats per minute
- a `sleep` sample which includes minutes spent in various sleep stages

{% image src="connect/sdk/sdk-samples.png" alt="Sahha Samples" width=512 / %}

{% callout title="Samples are fetched in realtime" %}

Using the `getSamples` method will fetch the most up-to-date samples for a [`SahhaSensor`](/docs/connect/sdk/collection#sahha-sensor).

This is very useful for monitoring the most recent changes in user activity.

For example, you can monitor changes in a user's heart rate.

If you'd like to check for new data continuously, you can call `getSamples(.heartRate)` with a timer (for example every 5 minutes).

{% /callout %}

{% callout title="Limiting the Date Range of Samples" type="warning" %}

**Although the `getSamples` method is free to use, it still requires time for the device to fetch samples.**

**The longer the date range you specify for this method, the longer it will take for samples to ready - potentially blocking your UI.**

If you are going to call `getSamples` using a timer, we recommend limiting the date range for new samples to match the interval you are polling (for example every 5 minutes).

{% /callout%}

---

## Get samples for the last hour

Using `getSamples` will return an array of samples for the `SahhaSensor` and time period you specify.

To get samples for the last hour, specify a `startDateTime` and `endDateTime` with a one hour difference.

Older samples will be at the start of the array.

Newer samples will be at the end of the array.

{% tabs %}

{% tab label="iOS" %}

```swift title=MyApp.swift
// Get samples for the last 24 hours
// Add a date range

let today = Date()
let lastHour = Calendar.current.date(byAdding: .hour, value: -1, to: today) ?? Date()

Sahha.getSamples(
    sensor: .steps,
    startDateTime: lastHour,
    endDateTime: today)
{ error, samples in
    if let error = error {
        print(error)
    } else if samples.isEmpty == false {
        print(samples)
    }
}
```

{% /tab %}

{% tab label="Android" %}

```kotlin title=MainActivity.kt
// Get samples for the last 24 hours
// Add a date range

Sahha.getSamples(
	sensor = SahhaSensor.steps,
  dates = Pair(LocalDateTime.now().minusHours(1), LocalDateTime.now())
    ) { error, samples ->
    error?.also {
        println(error)
    }
    samples?.also {
        println(samples)
    }
}
```

{% /tab %}

{% tab label="Flutter" %}

```typescript title=MyApp.dart
// Get samples for the last 24 hours
// Add a date range

SahhaFlutter.getSamples(
  sensor: SahhaSensor.steps,
  startDateTime: DateTime.now().subtract(const Duration(hours: 1)),
  endDateTime: DateTime.now())
.then((value) {
    List<dynamic> data = jsonDecode(value);
    debugPrint(data.toString());
}).catchError((error, stackTrace) => {debugPrint(error.toString())});
```

{% /tab %}

{% tab label="React Native" %}

```typescript title=MyApp.tsx
// Get samples for the last 24 hours
// Add date range as milliseconds since epoch time

let endDate: Date = new Date();
let startDate = new Date(endDate.setHours(endDate.getHours()-1);

Sahha.getSamples(
    SahhaSensor.steps,
    startDate.getTime(),
    endDate.getTime(),
    (error: string, value: string) => {
        if (error) {
            console.error(`Error: ${error}`);
        } else if (value) {
            const jsonArray = JSON.parse(value);
            const jsonString = JSON.stringify(jsonArray);
            console.log(value);
        }
    }
);
```

{% /tab %}

{% tab label="Ionic Capacitor" %}

```javascript title=MyApp.js
// Get samples for the last 24 hours
// Add date range as milliseconds since epoch time

let endDate: Date = new Date();
let startDate = new Date(endDate.setHours(endDate.getHours()-1);

Sahha.getSamples({
	sensor: SahhaSensor.steps,
	startDateTime: startDate.getTime(),
	endDateTime: endDate.getTime() })
.then(
    function (response) {
        const array = JSON.parse(response.value);
        const jsonString = JSON.stringify(array);
        console.log(jsonString);
    },
    function (error) {
        console.log(error);
    }
)
```

{% /tab %}

{% /tabs %}

---

## Get samples for the last day

Using `getSamples` will return an array of samples for the `SahhaSensor` and time period you specify.

To get samples for the last 24 hours, specify a `startDateTime` and `endDateTime` with a one day difference.

Older samples will be at the start of the array.

Newer samples will be at the end of the array.

{% tabs %}

{% tab label="iOS" %}

```swift title=MyApp.swift
// Get samples for the last 24 hours
// Add a date range

let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today) ?? Date()

Sahha.getSamples(
    sensor: .steps,
    startDateTime: yesterday,
    endDateTime: today)
{ error, samples in
    if let error = error {
        print(error)
    } else if samples.isEmpty == false {
        print(samples)
    }
}
```

{% /tab %}

{% tab label="Android" %}

```kotlin title=MainActivity.kt
// Get samples for the last 24 hours
// Add a date range

Sahha.getSamples(
	sensor = SahhaSensor.steps,
  dates = Pair(LocalDateTime.now().minusDays(1), LocalDateTime.now())
    ) { error, samples ->
    error?.also {
        println(error)
    }
    samples?.also {
        println(samples)
    }
}
```

{% /tab %}

{% tab label="Flutter" %}

```typescript title=MyApp.dart
// Get samples for the last 24 hours
// Add a date range

SahhaFlutter.getSamples(
  sensor: SahhaSensor.steps,
  startDateTime: DateTime.now().subtract(const Duration(days: 1)),
  endDateTime: DateTime.now())
.then((value) {
    List<dynamic> data = jsonDecode(value);
    debugPrint(data.toString());
}).catchError((error, stackTrace) => {debugPrint(error.toString())});
```

{% /tab %}

{% tab label="React Native" %}

```typescript title=MyApp.tsx
// Get samples for the last 24 hours
// Add date range as milliseconds since epoch time

let endDate: Date = new Date();
let days = endDate.getDate() - 1;
var startDate = new Date();
startDate.setDate(days);

Sahha.getSamples(
	SahhaSensor.steps,
	startDate.getTime(),
	endDate.getTime(),
	(error: string, value: string) => {
		if (error) {
			console.error(`Error: ${error}`);
		} else if (value) {
			const jsonArray = JSON.parse(value);
			const jsonString = JSON.stringify(jsonArray);
			console.log(value);
		}
	}
);
```

{% /tab %}

{% tab label="Ionic Capacitor" %}

```javascript title=MyApp.js
// Get samples for the last 24 hours
// Add date range as milliseconds since epoch time

let endDate: Date = new Date();
let days = endDate.getDate() - 1;
var startDate = new Date();
startDate.setDate(days);

Sahha.getSamples({
	sensor: SahhaSensor.steps,
	startDateTime: startDate.getTime(),
	endDateTime: endDate.getTime() })
.then(
    function (response) {
        const array = JSON.parse(response.value);
        const jsonString = JSON.stringify(array);
        console.log(jsonString);
    },
    function (error) {
        console.log(error);
    }
)
```

{% /tab %}

{% /tabs %}

---

## Sample response

Samples are returned as an array of objects in JSON format.

- **Parameters**:
  - `id`: UUID for the sample
  - `type`: The type of the sample (`steps`, `sleep`, etc.)
  - `startDateTime`: Start date-time in `"yyyy-MM-dd'T'HH:mm:ss.SSZZZZZ"` format (`"2021-10-27T16:34:06-06:00"`)
  - `endDateTime`: End date-time in `"yyyy-MM-dd'T'HH:mm:ss.SSZZZZZ"` format (`"2021-10-27T16:44:06-06:00"`)
  - `value`: Numerical value of the sample (`100`, `200`, etc.)
  - `unit`: The unit for measuring the value (`count`, `minute`, `kg`, `bpm`, etc.)
  - `source`: The source which recorded the sample in `com.company.app` format (`"com.apple.health"`)

**_For iOS and Android, samples are returned as an array of objects in `SahhaSample` format._**

{% tabs %}

{% tab label="iOS" %}

```swift title=SahhaSample.swift
public struct SahhaSample: Comparable, Codable {
    public var id: String
    public var type: String
    public var value: Double
    public var unit: String
    public var startDateTime: Date
    public var endDateTime: Date
    public var source: String
}
```

{% /tab %}

{% tab label="Android" %}

```kotlin title=SahhaSample.kt
data class SahhaSample(
    val id: String,
    val type: String,
    val value: Double,
    val unit: String,
    val startDateTime: ZonedDateTime,
    val endDateTime: ZonedDateTime,
    val source: String,
)
```

{% /tab %}

{% /tabs %}

### Array response

Samples are returned as an array of objects in JSON format.

Older samples will be at the start of the array.

Newer samples will be at the end of the array.

An example response includes these fields:

```json title=RESPONSE
[
	{
		"endDateTime": "2024-12-19T12:25:53.44+09:00",
		"source": "com.apple.health.0C1972B1-DBA3-4B25-9FE7-E9C00DF1DCE6",
		"unit": "count",
		"startDateTime": "2024-12-19T12:16:16.82+09:00",
		"value": 111,
		"type": "steps",
		"id": "4CD8C605-46CB-4349-B317-FFD984E5015A"
	},
	{
		"type": "steps",
		"source": "com.apple.health.0C1972B1-DBA3-4B25-9FE7-E9C00DF1DCE6",
		"startDateTime": "2024-12-19T12:35:09.56+09:00",
		"value": 198,
		"id": "3F16DFB3-6013-452A-95A0-EC89455F9059",
		"unit": "count",
		"endDateTime": "2024-12-19T12:40:52.96+09:00"
	},
	{
		"unit": "count",
		"id": "AA60B687-18BB-47EA-8541-D9EBE4788B82",
		"startDateTime": "2024-12-19T12:51:10.59+09:00",
		"source": "com.apple.health.0C1972B1-DBA3-4B25-9FE7-E9C00DF1DCE6",
		"value": 47,
		"endDateTime": "2024-12-19T12:56:36.07+09:00",
		"type": "steps"
	}
]
```

### Empty response

If no samples are found for the `SahhaSensor` and time period you specify, you will receive an error message.

```json title=RESPONSE
"No samples found"
```

---

## Using SahhaSensor

Samples are grouped by `SahhaSensor` type.

For example, use `getSamples(.heartRate)` to get samples of a user's heart rate.

{% callout title="Choose a SahhaSensor" %}

You must specify which `SahhaSensor` to use for `getSamples`.

{% /callout %}

|         SahhaSensor          |        Android         |          iOS           |
| :--------------------------: | :--------------------: | :--------------------: |
|            gender            | _Sensor Not Available_ | _Sensor Not Available_ |
|        date_of_birth         | _Sensor Not Available_ | _Sensor Not Available_ |
|            sleep             |           ✔           |           ✔           |
|            steps             |           ✔           |           ✔           |
|        floors_climbed        |           ✔           |           ✔           |
|          heart_rate          |           ✔           |           ✔           |
|      resting_heart_rate      |           ✔           |           ✔           |
|  walking_heart_rate_average  | _Sensor Not Available_ |           ✔           |
| heart_rate_variability_rmssd |           ✔           | _Sensor Not Available_ |
| heart_rate_variability_sdnn  | _Sensor Not Available_ |           ✔           |
|   blood_pressure_systolic    |           ✔           |           ✔           |
|   blood_pressure_diastolic   |           ✔           |           ✔           |
|        blood_glucose         |           ✔           |           ✔           |
|           vo2_max            |           ✔           |           ✔           |
|      oxygen_saturation       |           ✔           |           ✔           |
|       respiratory_rate       |           ✔           |           ✔           |
|     active_energy_burned     |           ✔           |           ✔           |
|     basal_energy_burned      | _Sensor Not Available_ |           ✔           |
|     total_energy_burned      |           ✔           | _Sensor Not Available_ |
|     basal_metabolic_rate     |           ✔           | _Sensor Not Available_ |
|       time_in_daylight       | _Sensor Not Available_ |           ✔           |
|       body_temperature       |           ✔           |           ✔           |
|    basal_body_temperature    |           ✔           |           ✔           |
|  sleeping_wrist_temperature  | _Sensor Not Available_ |           ✔           |
|            height            |           ✔           |           ✔           |
|            weight            |           ✔           |           ✔           |
|        lean_body_mass        |           ✔           |           ✔           |
|       body_mass_index        | _Sensor Not Available_ |           ✔           |
|           body_fat           |           ✔           |           ✔           |
|       body_water_mass        |           ✔           | _Sensor Not Available_ |
|          bone_mass           |           ✔           | _Sensor Not Available_ |
|     waist_circumference      | _Sensor Not Available_ |           ✔           |
|          stand_time          | _Sensor Not Available_ |           ✔           |
|          move_time           | _Sensor Not Available_ |           ✔           |
|        exercise_time         | _Sensor Not Available_ |           ✔           |
|       activity_summary       | _Sensor Not Available_ | _Sensor Not Available_ |
|         device_lock          | _Sensor Not Available_ | _Sensor Not Available_ |
|           exercise           |           ✔           |           ✔           |
|       energy_consumed        |           ✔           |           ✔           |
