Mobile SDK

Swift

Current Swift SDK Version: 2.3.2

Swift Package can be found here

Spike Swift SDK is a library on top of HealthKit that

  1. helps with the extraction of data.
  2. pushes data to SpikeAPI and delivers standardized data.

Requirements

  • iOS 13.0+
  • Xcode 14.2+
  • Swift 5+

Signing & Capabilities

To add HealthKit support to your application's Capabilities.

  • Open the folder of your project in Xcode
  • Select the project name in the left sidebar
  • Open Signing & Capabilities section
  • In the main view select + Capability and double click HealthKit
  • Allow Clinical Health Records and Background Delivery if needed..
Document image


More details you can find here.

Info.plist

Add Health Kit permissions descriptions to your Info.plist file.

Info.plist


Installation

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. To integrate SpikeSDK into your Xcode project using CocoaPods, specify it in your Podfile:

pod 'SpikeSDK'

Use pod install and pod update commands to install/update pods afterward.

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler. To integrate SpikeSDK into your Xcode project using Swift Package Manager, add it in your Package.swift or through the Project's Package Dependencies tab:

Swift


Alternatively, you can add a package dependency using Xcode.

Spike SDK Usage

Start getting Spike data in 3 steps. All Spike SDK async method calls should be wrapped into try catch block.

Create Spike connection

To set up the Spike SDK create SpikeConnection instance with appId, authToken, customerEndUserId and optional params callbackUrl, logger. From the 2.1.x version Spike SDK automatically manages connection persistance and restore connection if finds one with same appId, authToken and customerEndUserId. With each new connection creating call callbackUrl could be overridden. Provide SpikeLogger implementation to handle connection logs.

Swift


Permissions

Provide permissions to access iOS HealthKit data. Spike SDK method will check required permissions and request them if needed. Permission dialog may not be shown according on iOS permissions rules.

Swift


Extract data

There are two ways to get Spike data: to your webhook or directly in your app. Extract data methods optionally can be provided with date range. By providing range greater than one day samples array of result object will be empty. The maximum permitted date range is 90 days.

Extract Data Locally

According to the provided SpikeDataType result object may be different.

Swift

Swift


Extract data to webhook

Ensure callbackUrl was provided to SpikeConnection, otherwise you will get SpikeCallbackURLNotProvidedException error. Method will return job information object.

Swift

Swift


Background deliveries

Background delivery enables asynchronous data delivery to the customer backend by means of webhooks. It enables data updates to be sent to the backend even when the application is hidden or closed. Background delivery is only supported on iOS devices at the moment. Background deliveries will send whole day data to the webhook.

Configure for background deliveries

Under your project Signing & Capabilities section enable Background Delivery for HealthKit. Call Spike configure methods on each app start to trigger background deliveries tasks. Add Spike initialization code to your AppDelegate inside application:didFinishLaunchingWithOptions: method.

If you plan on supporting background delivery, you need to set up all observer queries in your app delegate. Spike SDK will do it by calling configure() method. Read more Receive Background Updates.

Swift


For SwiftUI based apps follow few steps:

  • Create a custom class that inherits from NSObject and conforms to the UIApplicationDelegate protocol, like this:
Swift

  • And now in your App scene, use the UIApplicationDelegateAdaptor property wrapper to tell SwiftUI it should use your AppDelegate class for the application delegate.
Swift


Register connection for background deliveries

Ensure callbackUrl was provided to SpikeConnection, otherwise you will get SpikeCallbackURLNotProvidedException error. Provide required Spike Data types to enableBackgroundDelivery method, it could be called after connection is created.

Swift

  • If dataTypes is not empty, then a daemon task is started which will listen for data updates coming from the platform and send them via webhooks in the background; the operation is not compound and each method call will override enabled background data types list;
  • If dataTypes parameter is empty or null, then background data delivery is stopped for this connection if it was enabled;

You can check if connection have active background deliveries listeners. If background delivery is not enabled, an empty set is returned.

Swift


Logging

Internally, the iOS SDK supports logging on various levels to assist with troubleshooting. However, to avoid imposing additional third-party dependencies on library users, the SDK expects a concrete logging implementation to be provided externally. This can be done by implementing the SpikeLogger class and providing it when creating a connection. Below is an example of how to implement a simple console logger.

Swift


Spike SDK provides background delivery process logs. This can be done by implementing the SpikeBackgroundDeliveriesLogger class and providing it though connection's setListener method. Below is an example of how to implement a simple console logger.

Swift


Data types

SpikeDataTypes.activitiesStream SpikeDataTypes.activitiesSummary SpikeDataTypes.breathing SpikeDataTypes.calories SpikeDataTypes.distance

SpikeDataTypes.glucose SpikeDataTypes.heart SpikeDataTypes.oxygenSaturation SpikeDataTypes.sleep SpikeDataTypes.steps

Classes

Spike

Class

Method

Description

Spike

createConnection

Creates a new SpikeConnection instance with the given user details.

Parameters: appId, authToken, customerEndUserId, callbackUrl, logger

Returns: An instance of the SpikeConnection class.

Spike

getBackgroundConnections

Returns all connections that are configured to deliver data in the background.

Returns: A collection (a set) of SpikeWebhookConnection instances.

Spike

ensurePermissionsAreGranted

Verifies that platform-specific permissions corresponding to the Spike data types provided are granted. In the event that some permissions are not granted, a platform-specific permissions dialogue will be presented to the end-user.

This method should only be invoked from a UI component

Parameters: permissions (Set<SpikeDataType>)

SpikeConnection

Class

Method

Description

SpikeConnection

getAppId

Retrieves the unique Spike application identifier.

Returns: string

SpikeConnection

getSpikeEndUserId

Retrieves the unique identifier assigned to the end-user by Spike.

Returns: string

SpikeConnection

getCustomerEndUserId

Retrieves the unique identifier assigned to the end-user by the customer.

Returns: string

SpikeConnection

close

Terminates any ongoing connections with Spike’s backend servers, clears any caches, and removes provided user details and tokens from the memory. Once the connection is closed, it cannot be used, and any method other than close() will throw a SpikeConnectionIsClosed exception.

SpikeConnection

extractData

Extracts local device data for the current date in the end-user’s time zone.

Parameters: dataType(SpikeDataType)

Returns: An instance of SpikeData. The concrete type will depend on the data type requested.

SpikeConnection

extractData

Extracts local device data for the given time range. The maximum allowed single-query time interval is 7 days. If required, data of any longer time period can be accessed by iterating multiple queries of 7 days.

Parameters: dataType(SpikeDataType), from(DateTime), to(DateTime)

Returns: An instance of SpikeData. The concrete type will depend on the data type requested.

SpikeConnection

extractAndPostData

Extracts local device data for the current date in the local user time zone and sends it as a webhook notification to the customer’s backend. Optionally time range can be provided.

*On iOS, the maximum allowed single-query time interval is 90 days. If required, data of any longer period can be accessed by iterating multiple queries of 90 days.

Parameters: config (SpikeExtractConfig)

SpikeWebhookConnectionListener

Abstract class allowing to receive notifications from the background data delivery process.

Class

Method

Description

SpikeWebhookConnectionListener

onSubmissionFailure

Invoked on an asynchronous data submission failure.

Parameters: webhookJob (SpikeWebhookJob), exception (SpikeException)

Errors and Exceptions

SpikeException

The abstract parent of all concrete exceptions.

SpikeConnectionIsClosedException

Thrown if any method is invoked on SpikeConnection or one of its subclasses after the connection has been closed.

SpikeInvalidCredentialsException

Thrown if the credentials provided are not recognised, i.e. are invalid or expired.

SpikeInvalidDateRangeException

Thrown if duration exceeds the allowed maximum or if ‘from’ date is greater than ‘to’ date. The message will contain a specific cause description.

SpikeInvalidCallbackUrlException

Thrown if the callback URL is not a valid URL, does not have HTTPS schema, or is not a sub-URL of the main callback URL configured for the application. The exception message will contain a specific reason.

SpikePackException

Thrown when a connection cannot be serialised to a packed state. The exception cause will contain the underlying error.

SpikePermissionsNotGrantedException

Thrown when Spike SDK is unable to access the data due to permissions not being granted.

SpikeServerException

Whenever any operation with the Spike backend fails and the error does not fall into any of the above exceptions. The exception cause will contain the underlying error.

SpikeUnpackException

Thrown when a connection cannot be deserialised from a packed state. The exception cause will contain the underlying error.