website logo
⌘K
Quickstart
User
Metrics
Webhooks
Mobile SDK
V2
React Native
Flutter
Android (Kotlin)
Swift
V1
Errors
FAQ
Docs powered by
Archbee
Mobile SDK
V2

Swift

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 13.0+
  • 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.
Document image


More details you can find here.

Info.plist

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

Info.plist
|
<key>NSHealthShareUsageDescription</key>
<string>We will use your health information to better track workouts.</string>

<key>NSHealthUpdateUsageDescription</key>
<string>We will update your health information to better track workouts.</string>

<key>NSHealthClinicalHealthRecordsShareUsageDescription</key>
<string>We will use your health information to better track  workouts.</string>


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', '2.1.10'

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

Configuration

1. Import Spike to your project.

import Spike

2. Add Spike initialization (could be configuration) code to application(_:didFinishLaunchingWithOptions:) in your AppDelegate file.

Spike.configure()

3. To set up the Swift SDK, please provide the application ID, authentication token, and your customer user ID. You can find the application ID and authentication token in the Spike developer console. Personal identifiable information, such as emails, should not be part of user IDs.

Swift
|
import Spike
// APP ID and APP TOKEN from Spike developer console
var conn = Spike.createConnection(
  appId: 'my_app_id'
  authToken: 'my_app_access_token',
  customerEndUserId: 'my_user_id'
);


Getting and using data

Once a connection has been created data can be retrieved using the extractData method. The below example shows how to retrieve daily steps for today which are returned as part of the activities summary (An instance of SpikeData). The concrete type will depend on the data type requested.

Swift
|
// conn was created in the previous step

/*
* Extracting activities summary data for today.
*/
var activitiesSummary = conn.extractData(
  dataType: SpikeDataTypes.activitiesSummary
);

/*
* Accessing daily steps.
*/
print("Steps: \(activitiesSummary.getEntries()[0].steps)")


Extracting data by time range

Params from and to enable the extraction of 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.

Swift
|
let calendar = Calendar.current

let toDate = Date() // Today's date

let fromDate = calendar.date(byAdding: .day, value: -5, to: toDate)!

var activitiesSummary = conn.extractData(
  dataType: SpikeDataTypes.activitiesSummary,
  from: fromDate,
  to: toDate
)



Sending data to webhook

Extracts local device data for the given time range and sends it as a webhook notification to the customer’s backend.

Swift
|
import Spike

var conn = Spike.createConnection(
  appId: 'my_app_id'
  authToken: 'my_app_access_token',
  customerEndUserId: 'my_user_id',
  callbackUrl: 'https://example.com/data'
);

/*
* Extracting and sending activities summary data.
*/
var response = conn.extractAndPostData(
  dataType: SpikeDataTypes.activitiesSummary,
  from: fromDate,
  to: toDate
)



Background Delivery

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.

Signing & Capabilities

Go to your target’s Signing & Capabilities section and add Background Modes.

Allow Background fetch.

Info.plist

Add background task identifier to app Info.plist file. And check Info.plist for UIBackgroundModes.

Info.plist
|
...
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
    <string>com.spike.sdk.task.update</string>
</array>
...
<key>UIBackgroundModes</key>
<array>
    <string>fetch</string>
</array>
...


Example

Swift
|
import Spike

var conn = Spike.createConnection(
  appId: 'my_app_id'
  authToken: 'my_app_access_token',
  customerEndUserId: 'my_user_id',
  callbackUrl: 'https://example.com/data'
);

/*
* Enabling background delivery.
*/
conn.enableBackgroundDelivery(
  dataTypes: [SpikeDataTypes.activitiesSummary]
);




  • 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 new data types replace any previously configured ones should they exist;
  • If dataTypes parameter is empty or null, then background data delivery is stopped for this connection if it was enabled;
  • Function conn.getBackgroundDeliveryDataTypes gets the data types for which background delivery is enabled. If background delivery is not enabled, an empty set is returned.

Logging

Internally, the Swift 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 or unpacking a connection.

Below is an example of how to implement a simple console logger.

Swift
|
class ConsoleLogger: SpikeLogger {
    func isDebugEnabled() -> Bool {
        return true
    }
    
    func isInfoEnabled() -> Bool {
        return true
    }
    
    func isErrorEnabled() -> Bool {
        return true
    }
    
    func debug(_ message: String) {
        print("DEBUG: \(message)")
    }
    
    func info(_ message: String) {
        print("INFO: \(message)")
    }
    
    func error(_ message: String) {
        print("ERROR: \(message)")
    }
}

var conn = SpikeSdk.createConnection(
  appId: 'my_app_id'
  authToken: 'my_app_access_token',
  customerEndUserId: 'my_user_id',
  logger: ConsoleLogger()
);


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, logger

Returns: An instance of the SpikeConnection class.

Spike

createConnection

Creates a new connection instance with the given user details that is capable of delivering data to the customer backend via webhooks.

Parameters: appId, authToken, customerEndUserId, callbackUrl, logger

Returns: An instance of the SpikeWebhookConnection class.

Spike

unpackConnection

Restores a connection instance from a previously serialised state. A connection cannot be unpacked if a strong reference to a connection with the same session ID already exists.

Parameters: connection, logger

Returns: An instance of the SpikeConnection or SpikeWebhookConnection class. The method return type should be that of a base class, i.e., SpikeConnection.

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

pack

Creates a string representation of the connection state. This method facilitates the persistence of connections.

Returns: String

SpikeWebhookConnection

Class

Method

Description

SpikeWebhookConnection

getAppId

Retrieves the unique Spike application identifier.

Returns: string

SpikeWebhookConnection

getSpikeEndUserId

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

Returns: string

SpikeWebhookConnection

getCustomerEndUserId

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

Returns: string

SpikeWebhookConnection

getCallbackUrl

Returns the URL that will receive webhook notifications.

SpikeWebhookConnection

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.

SpikeWebhookConnection

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.

SpikeWebhookConnection

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.

SpikeWebhookConnection

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.

Parameters: dataType(SpikeDataType)

SpikeWebhookConnection

extractAndPostData

Extracts local device data for the given time range and sends it as a webhook notification to the customer’s backend.

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

SpikeWebhookConnection

enableBackgroundDelivery

Enables background data delivery for selected data types. No-op on Android (for now).

Parameters: dataType(SpikeDataType)

SpikeWebhookConnection

getBackgroundDeliveryDataTypes

Gets the data types for which background delivery is enabled. If background delivery is not enabled, an empty set is returned.

Returns: Returns: A collection (a set) of SpikeDataType objects.

SpikeWebhookConnection

pack

Creates a string representation of the connection state. This method facilitates the persistence of connections.

Returns: String

SpikeWebhookConnection

setListener

Sets a listener that is to handle notifications from the background delivery process.

Parameters: listener

(SpikeWebhookConnectionListener)

  • If listener is not null, then any existing listener is replaced
  • If listener is null, then any existing listener is removed

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.

Did this page help you?
PREVIOUS
Android (Kotlin)
NEXT
V1
Docs powered by
Archbee
TABLE OF CONTENTS
Requirements
Signing & Capabilities
Info.plist
Installation
CocoaPods
Configuration
Getting and using data
Extracting data by time range
Sending data to webhook
Background Delivery
Signing & Capabilities
Info.plist
Example
Logging
Data types
Classes
Spike
SpikeConnection
SpikeWebhookConnection
SpikeWebhookConnectionListener
Errors and Exceptions
SpikeException
SpikeConnectionIsClosedException
SpikeInvalidCredentialsException
SpikeInvalidDateRangeException
SpikeInvalidCallbackUrlException
SpikePackException
SpikePermissionsNotGrantedException
SpikeServerException
SpikeUnpackException
Docs powered by
Archbee