iOS (Swift)
SDK Installation
RealTime streaming on iOS is only available to those registered on the Apple Developer Program
Summary:
Add https://github.com/tryterra/TerraRTiOS as a package dependency
In your info.plist, add:
Privacy - Bluetooth Always Usage Description
: Justification for BLE usage (shown to the user when requesting permission)Privacy - Motion Usage Description
: Justification for phone motion sensor usage (shown to the user when requesting permission - only add if using phone sensors for streaming)
When the app is launched for the first time, these permissions will be requested from the user.
Connection setup/management
The SDK revolves around the TerraRT
class, which manages Bluetooth connections and real-time data streaming.
SDK Initialization
To do this, run the TerraRT manager initialization function as below:
import TerraRT
let developerId = "yourDeveloperId" // Replace with your actual developer ID
let referenceId: String? = "yourReferenceId" // This is optional; can be nil
// Initialize TerraRT
let terraRT = TerraRT(devId: developerId, referenceId: referenceId) { success in
if success {
print("TerraRT initialization successful!")
// Perform further actions if needed
} else {
print("TerraRT initialization failed.")
// Handle failure case
}
}
Initializing a Connection
Register the phone by calling initConnection
.
This connects the phone to Terra, allows you to use other SDK functions, and allows it to be a producer once a wearable is connected later on.
Use the terraRT instance created above and call initConnection as below:
let token = "yourAuthToken" // Replace with your actual token
// Call the initConnection function with the token
terraRT.initConnection(token: token) { success in
if success {
print("Connection initialized successfully!")
// Perform further actions after a successful connection
} else {
print("Failed to initialize connection.")
// Handle failure case
}
}
To generate the token, make the below call from your backend
Creates a token to be used with initConnection() functions in the Terra mobile SDKs in order to create a user record for Apple Health or Samsung Health (or equivalent)
your developer ID
testingTerra
your API key
OtHJok60oQmT8zhnUWc4SWBJI7ztPTs88C0gOsJJ
POST /v2/auth/generateAuthToken HTTP/1.1
Host: api.tryterra.co
dev-id: text
x-api-key: text
Accept: */*
{
"status": "success",
"token": "250c68b9c21b78e40e7a3285a2d538d3bc24aabd3b4c76a782fb0a571ca4501d",
"expires_in": 180
}
Connecting a device
iOS devices only support connection via BLE or Apple Watch's custom bluetooth protocol. For the Apple Watch connection, refer to the guide below
You may use an example as below to call the startBluetoothScan function, which pulls up a modal allowing the user to select a wearable to connect
import SwiftUI
import TerraRTSDK // Assuming the SDK is imported as TerraRTSDK
struct BluetoothScanView: View {
@State private var showScanWidget = false
@State private var scanSuccess = false
var body: some View {
VStack {
if showScanWidget {
// Show the TerraBLEWidget which is returned by the scan function
terraRT.startBluetoothScan(type: .BLE) { success in
scanSuccess = success
if success {
print("Bluetooth scan and connection successful!")
} else {
print("Bluetooth scan failed.")
}
}
// Optionally, handle success/failure states within the UI
} else {
Button(action: {
startScan()
}) {
Text("Start Bluetooth Scan")
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
}
}
if scanSuccess {
Text("Scan successful! Device connected.")
.foregroundColor(.green)
} else if showScanWidget && !scanSuccess {
Text("Scanning for devices...")
}
}
.padding()
}
// Function to start the scan and show the TerraBLEWidget
func startScan() {
showScanWidget = true
}
}
// Example of how to use the BluetoothScanView
struct ContentView: View {
var body: some View {
BluetoothScanView()
}
}
Streaming Real-Time Data
Once the phone is registered and you've connected a wearable, you can stream data from the wearable to your mobile app.
Start Streaming
You can start receiving data from the connected wearable's stream by calling startRealtime
with the following signature
func startRealtime(type: TerraRTiOS.Connections, dataType: Swift.Set<TerraRTiOS.DataTypes>, callback: @escaping (TerraRTiOS.Update) -> Swift.Void)
you can also stop the stream and disconnect the wearable once done
import TerraRT
// Example function to start real-time data streaming, stop it, and disconnect
func manageRealtimeData() {
let connectionType: TerraRTiOS.Connections = .BLE // Replace with your connection type (e.g., BLE)
let dataTypes: Set<TerraRTiOS.DataTypes> = [.heartRate, .steps] // Replace with desired data types to stream
// Start real-time data streaming
terraRT.startRealtime(type: connectionType, dataType: dataTypes) { update in
handleUpdate(update: update)
}
// Stop the real-time streaming after some action or condition
// Example: stopping after a delay (5 seconds here, for demonstration)
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
terraRT.stopRealtime(type: connectionType)
print("Real-time streaming stopped.")
}
// Optionally, disconnect after stopping the real-time data stream
DispatchQueue.main.asyncAfter(deadline: .now() + 7) {
terraRT.disconnect(type: connectionType)
print("Disconnected from connection.")
}
}
// Function to handle updates from the real-time data stream
func handleUpdate(update: TerraRTiOS.Update) {
// Process the real-time data update here
print("Received update at timestamp: \(update.ts)")
print("Update type: \(update.type)")
if let value = update.val {
print("Value: \(value)")
}
if let dataArray = update.d {
print("Array of data values: \(dataArray)")
}
}
// Call the function to start the real-time data management process
manageRealtimeData()
WatchOS Integration
Setup
Create a WatchOS target within your iOS project:
File -> New -> Target -> Watch App for iOS App.
Enable HealthKit and Background Modes for the WatchOS app, and add the following privacy keys to your
Info.plist
:Privacy - Health Share Usage Description
Privacy - Health Update Usage Description
Privacy - Health Records Usage Description
Start Streaming from WatchOS
To begin streaming data from Apple Watch, call the startStream()
function from within the Watch app. This will initiate data streaming from the Watch sensors to the paired iOS app.
On the iOS app, you'll equivalently need to listen for updates from the WatchOS app:
Reading a data stream on iOS will only be possible if you have previously created a connection
import WatchKit
import TerraRTiOS
class InterfaceController: WKInterfaceController {
var terraRT: Terra?
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Initialize Terra SDK on watchOS
do {
terraRT = try Terra()
terraRT?.connect()
print("Terra SDK initialized on watchOS")
startStreamingData()
} catch {
print("Failed to initialize Terra SDK: \(error)")
}
}
// Start streaming real-time data (e.g., heart rate and steps)
@IBAction func startStreamingData() {
let dataTypes: Set<TerraRTiOS.ReadTypes> = [.HEART_RATE, .STEPS]
terraRT?.startStream(forDataTypes: dataTypes) { success, error in
if success {
print("Streaming started")
} else {
print("Failed to start streaming: \(error?.localizedDescription ?? "Unknown error")")
}
}
}
// Stop streaming real-time data
@IBAction func stopStreamingTapped() {
terraRT?.stopStream()
print("Streaming stopped")
}
}
Streaming Workouts from WatchOS
The Apple Watch app can also manage a workout session, during which recording frequency is enhanced.
To manage a workout session, you can use the following convenience functions:
From the Watch:
startExercise
stopExercise
resumeExercise
pauseExercise
From the iOS app:
pauseWatchOSWorkout
resumeWatchOSWorkout
stopWatchOSWorkout
Here is an example template of the watchOS app using the functions outlined above
import WatchKit
import TerraRTiOS
class InterfaceController: WKInterfaceController {
var terraRT: Terra?
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Initialize Terra SDK on watchOS
do {
terraRT = try Terra()
terraRT?.connect()
print("Terra SDK initialized on watchOS")
} catch {
print("Failed to initialize Terra SDK: \(error)")
}
}
// Start an exercise session (e.g., Running) using TerraRT
@IBAction func startExerciseTapped() {
terraRT?.startExercise(forType: .RUNNING) { success, error in
if success {
print("Running exercise started on watchOS")
} else {
print("Failed to start exercise: \(error?.localizedDescription ?? "Unknown error")")
}
}
}
// Pause the exercise session using TerraRT
@IBAction func pauseExerciseTapped() {
terraRT?.pauseExercise()
print("Exercise paused")
}
// Resume the exercise session using TerraRT
@IBAction func resumeExerciseTapped() {
terraRT?.resumeExercise()
print("Exercise resumed")
}
// Stop the exercise session using TerraRT
@IBAction func stopExerciseTapped() {
terraRT?.stopExercise { success, error in
if success {
print("Exercise stopped on watchOS")
} else {
print("Failed to stop exercise: \(error?.localizedDescription ?? "Unknown error")")
}
}
}
// Start streaming real-time data (e.g., heart rate and steps)
@IBAction func startStreamingTapped() {
let dataTypes: Set<TerraRTiOS.ReadTypes> = [.HEART_RATE, .STEPS]
terraRT?.startStream(forDataTypes: dataTypes) { success, error in
if success {
print("Streaming started")
} else {
print("Failed to start streaming: \(error?.localizedDescription ?? "Unknown error")")
}
}
}
// Stop streaming real-time data
@IBAction func stopStreamingTapped() {
terraRT?.stopStream()
print("Streaming stopped")
}
}
Last updated
Was this helpful?