Link Search Menu Expand Document
Developer | Sahha

SDK


Table of contents
  1. Repository
  2. Installation
    1. Option A) Swift Package Manager
    2. Option B) CocoaPods
    3. Import Module
  3. Project Settings
  4. Configure
    1. Option A) SwiftUI
    2. Option B) UIKit
    3. Settings
  5. Profile
    1. Authenticate
    2. Demographic
  6. Sensors
    1. Sensor Status
    2. Enable Sensor
    3. Open App Settings
    4. Post Sensor Data
  7. Analyze

Repository

You can browse the Sahha iOS SDK on Github.

iOS SDK [GitHub]


Installation

Option A) Swift Package Manager

Add the Sahha swift package to your project’s Package Dependencies.

https://github.com/sahha-ai/sahha-swift

Option B) CocoaPods

Step 1) Add the Sahha pod to your project’s Podfile.

Podfile

 pod 'Sahha'

Step 2) Run pod install inside your project root folder.

Terminal

$ pod install

Import Module

Import the Sahha module into any files inside your project that use the SDK.

Swift

import Sahha

Project Settings

Add NSMotionUsageDescription to your Xcode project’s Info.plist.

Add NSHealthShareUsageDescription to your Xcode project’s Info.plist.

Add NSHealthUpdateUsageDescription to your Xcode project’s Info.plist.

You will need to write a message explaining to the user why they should approve these permissions.

Info.plist

<key>NSMotionUsageDescription</key>
  <string>This app would like access to your motion activity for analysis.</string>
<key>NSHealthShareUsageDescription</key>
  <string>This app would like access to your health activity for analysis.</string>
<key>NSHealthUpdateUsageDescription</key>
  <string>This app would like access to your health activity for analysis.</string>

Add HealthKit entitlement to your Xcode project. Select your App Target in the Project panel, then Signing & Capabilities, then tap the + button, then select HealthKit from the list.

App.entitlements

<key>com.apple.developer.healthkit</key>
  <true/>

Configure

The Sahha SDK must be configured immediately on app launch.

Option A) SwiftUI

Configure Sahha inside onAppear of your app’s ContentView.

SwiftUI

ContentView().onAppear {
    let settings = SahhaSettings(environment: .development, sensors: [.sleep], postSensorDataManually: false)
    Sahha.configure(settings)
}

Option B) UIKit

Configure Sahha inside application didFinishLaunchingWithOptions of your app’s AppDelegate.

UIKit

func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
    let settings = SahhaSettings(environment: .development, sensors: [.sleep], postSensorDataManually: false)
    Sahha.configure(settings)
}

Settings

You may pass an optional list of settings to the configure method.

The SahhaEnvironment determines if the SDK connects to the development or production server of the API. Setting this incorrectly will send data to the wrong server.

SahhaEnvironment Description
development For development and testing
production For submission to the App store
public enum SahhaEnvironment: String {
    case development
    case production
}

Which sensors do you want to enable? Passing an empty array will enable all sensors by default.

SahhaSensor Description Android iOS
sleep For tracking sleep patterns
pedometer For tracking walking patterns
device For tracking device usage patterns X
public enum SahhaSensor: String, CaseIterable {
    case sleep
    case pedometer
    case device
}

If you would like to handle posting of sensor data to the Sahha API manually, set postSensorDataManually to true. You will then need to post sensor data to the Sahha API manually by calling postSensorData.

If you would like the Sahha SDK to handle posting of sensor data to the Sahha API automatically, set postSensorDataManually to false.

postSensorDataManually defaults to false.

postSensorDataManually Description
true You will post sensor data to the Sahha API manually by calling postSensorData
false The Sahha SDK will post sensor data to the Sahha API automatically

Profile

Each user of your app will be assigned a Sahha Profile for analyzation. This is not handled by the Sahha SDK. Please refer to the separate Sahha API documentation for steps to generate profiles and profile tokens.

Authenticate

The Sahha SDK must be authenticated in order to connect to the Sahha API. Do this once per user profile. Once the user is successfully authenticated, the SDK will take care of automatically refreshing expired tokens.

Sahha.authenticate(token: "PROFILE_TOKEN", refreshToken: "REFRESH_TOKEN")

Demographic

Each authenticated profile includes an optional demographic which can be used to increase the accuracy of analyzation. This data is not collected automatically. Your app can choose to GET or POST this demographic to the Sahha API.

public struct SahhaDemographic: Codable {
    public var age: Int?
    public var gender: String? // "Male", "Female", "Gender Diverse"
    public var country: String? // ISO 2 digit code, i.e. "US", "UK", "AU", etc.
    public var birthCountry: String?  // ISO 2 digit code, i.e. "US", "UK", "AU", etc.
}

Sahha.postDemographic(demographic) { error, success in
    if let error = error {
        print(error)
    }
    print(success)
}

Sahha.getDemographic() { error, demographic in
    if let error = error {
        print(error)
    }
    if let demographic = demographic {
        print(demographic)
    }
}

Sensors

The Sahha SDK acts as a bridge between your app and the device sensors. You must enable each sensor that you want to start collecting data from. To optimize your analysis result, we suggest enabling all available sensors.

public enum SahhaSensor: String, CaseIterable {
    case sleep
    case pedometer
    case device
}

Sensor Status

Each sensor has multiple possible statuses.

public enum SensorStatus: Int {
    case pending /// Sensor is pending User permission
    case unavailable /// Sensor is not supported by the User's device
    case disabled /// Sensor has been disabled by the User
    case enabled /// Sensor has been enabled by the User
}

You can check the current status of each sensor by calling getSensorStatus. This method is asynchronous and will return the updated SahhaSensorStatus in its callback.

Sahha.getSensorStatus(SahhaSensor.pedometer) { newStatus in
    print(newStatus.description)
}

Enable Sensor

You will need to manually enable each sensor by calling enableSensor. This method is asynchronous and will return the updated SahhaSensorStatus in its callback.

Sahha.enableSensor(SahhaSensor.pedometer) { newStatus in
    print(newStatus.description)
}

Open App Settings

It’s possible for your app user to disable a sensor. In this case, you must send the user to the app settings to manually enable the sensor.

Sahha.openAppSettings()

NOTICE: If the user enables / disables a sensor permission from the device settings menu while your app is in the background, the iOS system will force your app to terminate. This is intentional behavior and your app will need to be relaunched.

Post Sensor Data

By default, the Sahha SDK will post sensor data automatically. However, if you set postSensorDataManually to true, you will need to post sensor data manutally to the Sahha API by calling postSensorData at a regular interval of your choosing.

You have two options:

  • A) Include a list of specific sensor data you want to post
  • B) Post all sensor data

Option A) Post specific sensor data

// Include a list of sensors
Sahha.postSensorData(sensors: [SahhaSensor.device]) { error, success in
    if let error = error {
        print(error)
    }
    print(success)
}

Option B) Post all sensor data

// Leave sensor list empty
Sahha.postSensorData() { error, success in
    if let error = error {
        print(error)
    }
    print(success)
}

Analyze

You can analyze a user’s activities over a period of time and receive a mental health personalized report which you can display or action within your app.

// Analyze Previous 24 Hours
Sahha.analyze { error, json in
    isAnalyzeButtonEnabled = true
    if let error = error {
        print(error)
    } else if let json = json {
        print(json)
    }
}

// Analyze Previous 7 Days
let today = Date()
let sevenDaysAgo = Calendar.current.date(byAdding: .day, value: -7, to: today) ?? Date()
Sahha.analyze(dates: (sevenDaysAgo, today)) { error, json in
    isAnalyzeButtonEnabled = true
    if let error = error {
        print(error)
    } else if let json = json {
        print(json)
    }
}

The response will be in JSON format. An example response includes these fields:

{
  "inferences": [
    {
      "createdAt": "2022-05-20T00:30:00+00:00",
      "modelName": "automl_toolkit_randomForest",
      "predictionState": "not_depressed",
      "predictionSubState": "",
      "predictionRange": -1,
      "predictionConfidence": 0.8,
      "dataSource": ["sleep", "screenTime"],
      "dataSourceSummary": [
        {
          "type": "sleep",
          "amount": "0"
        },
        {
          "type": "screenTime",
          "amount": "0"
        }
      ]
    }
  ]
}