Roam.ai Docs
HomeContactDashboard
Roam v3
Roam v3
  • Introduction
    • Overview
    • Getting Started
  • Frameworks
    • Android
  • iOS
  • React Native
  • DATA DELIVERY
    • AWS S3
  • Others
    • EchoPulse
    • FAQ
Powered by GitBook
On this page
  • Prerequisites
  • Step 1: Install the SDK
  • 1.1 Add Roam SDK to Your Podfile
  • 1.2 Install Dependencies
  • 1.3 Import the SDK
  • Step 2: Initialize the SDK
  • 2.1 Configure Your AppDelegate
  • Step 3: Request Location Permissions
  • 3.1 Update Info.plist
  • 3.2 Request Permission in Code
  • Step 4: Start and Stop Location Tracking
  • Start Tracking
  • Stop Tracking
  • Step 5: Receive Location Updates
  • Implement RoamDelegate
  • Step 6: Enable and Configure Batch Sync
  • 6.1 Enable Batch Transmission
  • 6.2 Customize What Gets Sent (Optional)
  • Disabling Batch Sync
  • Data Included in Batch Location Updates
  • 🎉 You’re All Set!

Was this helpful?

Export as PDF

iOS

PreviousAndroidNextReact Native

Last updated 13 days ago

Was this helpful?

The Roam iOS SDK enables continuous, battery-efficient location tracking in iOS apps. This guide walks you through integrating the SDK — from installation to receiving real-time updates — with an optional setup for batch sync and data enrichment.

Prerequisites

Before you begin:

  • Access to the

  • A project created with your app’s Bundle ID

  • Your PUBLISHABLE_KEY from the dashboard

  • Xcode 14.0 or later

  • iOS 12+

Already set up your project on the dashboard? If not, follow the instructions in the section.

Important: Make sure your Bundle ID matches exactly with the one added on the Roam Dashboard. The SDK will not initialize if they differ.

Step 1: Install the SDK

The first step in integrating the Roam iOS SDK is to add the necessary dependencies to your project using CocoaPods. This ensures that your app can download and link the SDK from Roam’s hosted repository.

1.1 Add Roam SDK to Your Podfile

Open your project’s Podfile and add the following line:

Podfile
pod 'roam-ios', '0.1.31'
pod 'roam-ios/RoamBatchConnector', '0.1.33'

1.2 Install Dependencies

In your terminal, navigate to your project directory and run:

pod install

Once installed, open the .xcworkspace file to continue development.

1.3 Import the SDK

Open your AppDelegate.swift and import the SDK at the top of the file:

import Roam
import RoamBatchConnector
✅ What You Should See After a Successful Setup

Once the SDK is installed:

  • The Roam pod should appear under your Pods group in Xcode

  • You should be able to import Roam without errors

  • Auto-complete should work for SDK classes like Roam, RoamLocation, RoamDelegate

🧪 Test Tip: Try typing Roam. in any Swift file — if Xcode shows method suggestions, the SDK was installed successfully.

Step 2: Initialize the SDK

After installing the SDK, the next step is to initialize it when your app launches. Initialization tells the Roam SDK which project it belongs to and prepares it to begin location tracking.

2.1 Configure Your AppDelegate

Open AppDelegate.swift and update the application(_:didFinishLaunchingWithOptions:) method as follows:

AppDelegate.swift
import UIKit
import Roam

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, RoamDelegate {

    var window: UIWindow?

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        
        // Initialize Roam with your publishable key
        Roam.initialize("YOUR_PUBLISHABLE_KEY")
        
        // Assign delegate to receive location updates
        Roam.delegate = self

        return true
    }
}

Replace "YOUR_PUBLISHABLE_KEY" with the actual key from your Roam Dashboard.

Always call Roam.initialize(...) inside didFinishLaunchingWithOptions. Calling it too early (like in a custom initializer or another part of the app lifecycle) may lead to tracking failures or errors like MotionStatus.ERROR_INITIALIZE, especially on first launch.

✅ What You Should See After a Successful Setup
  • The app should build and launch without crashing

  • No initialization errors should appear in the Xcode console

  • Roam methods like Roam.startTracking(...) should now work without warnings

🧪 Test Tip: Add a simple log after initialization to confirm it runs:

print("✅ Roam SDK Initialized")

This log should appear in your Xcode console when the app starts.

Step 3: Request Location Permissions

To start tracking location, your app must request the appropriate permissions from the user. iOS supports various permission levels like When In Use and Always, and each affects how the Roam SDK behaves — especially in background scenarios.

3.1 Update Info.plist

Open your Info.plist and add the following keys and descriptions:

Info.plist
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>We need your location to provide continuous tracking, even in the background.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>We need your location while using the app.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>We use your location to support key features even when the app is closed.</string>

These strings are shown to users in system permission prompts.

3.2 Request Permission in Code

You should call Roam.requestLocation() only after the SDK has finished initializing. We recommend delaying it by a second or two to avoid race conditions on cold starts:

DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
    Roam.requestLocation()
}

This method triggers the system dialog prompting the user to allow location access.

ℹ️ Permission Levels Explained
  • While Using the App: Access granted only when the app is in the foreground. Works for basic tracking.

  • Always: Access granted at all times — needed for background updates.

  • Ask Every Time: iOS will re-prompt each time, which may impact tracking consistency.

  • Never: No location access — tracking will not function.

On first launch, iOS might not show the "Always" prompt. It often appears later — typically when background tracking is triggered for the first time.

✅ What You Should See After a Successful Setup
  • iOS will display the location permission prompt the first time Roam.requestLocation() is called.

  • If the user grants permission, you can confirm via system settings or start tracking immediately.

  • If permission is denied, you can handle it using delegate callbacks or guide users to settings.

🧪 Test Tip: Test on a real device. Simulators may not always show the correct behavior for background location or "Always" permissions.

Step 4: Start and Stop Location Tracking

Once the SDK is initialized and permissions are granted, you’re ready to start tracking location. This step covers how to begin and stop location tracking using Roam’s built-in methods.

Start Tracking

To start tracking, call the Roam.startTracking() method. This begins collecting location updates — optimized for both accuracy and battery life.

You can trigger tracking wherever it fits your flow (e.g., after login or when entering a specific screen):

Roam.startTracking(.balanced) { status, error in
    if let error = error {
        print("Error starting tracking: \(error.localizedDescription)")
    } else {
        print("✅ Tracking started: \(status ?? "Success")")
    }
}

We recommend using .balanced tracking mode for a strong balance between battery life and update frequency. This is the default mode for most production use cases.

⚠️ Common Error Messages

If tracking fails to start, the SDK may return one of the following errors:

Code
Message

GS403

Location services error or permissions not granted

GS403

Offline Tracking Disabled

Stop Tracking

To stop tracking at any time (e.g., when the user logs out or tracking is no longer needed):

Roam.stopTracking { status, error in
    if let error = error {
        print("Error stopping tracking: \(error.localizedDescription)")
    } else {
        print("🛑 Tracking stopped: \(status ?? "Success")")
    }
}

This is useful for scenarios such as:

  • User signs out of the app

  • You need location tracking only during specific workflows

  • You want to pause tracking during inactivity

✅ What You Should See After a Successful Setup
  • When tracking starts: Console will log Tracking started: Success

  • When tracking stops: Console will log Tracking stopped: Success

  • Roam will begin delivering location updates (see next step)

  • If an error occurs (e.g. permissions not granted), the error will be returned in the callback

🧪 Test Tip: Start tracking, then move around with the device (real or simulator). You should see location logs via the RoamDelegate method. Stop tracking and confirm that no additional updates are received.

Step 5: Receive Location Updates

Once tracking is active, the Roam SDK will begin delivering location updates to your app. To receive and handle these updates, your app must implement the RoamDelegate protocol.

Implement RoamDelegate

In your AppDelegate.swift (or any other class you'd like to handle location updates), conform to the RoamDelegate protocol:

AppDelegate.swift
import Roam
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, RoamDelegate {

    var window: UIWindow?

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        Roam.initialize("YOUR_PUBLISHABLE_KEY")
        Roam.delegate = self
        return true
    }

    // 🔄 Called whenever a new location update is available
    func didUpdateLocation(_ locations: [RoamLocation]) {
        if let location = locations.first {
            let lat = location.location.coordinate.latitude
            let lng = location.location.coordinate.longitude
            let speed = location.speed
            let recordedAt = location.recordedAt
            print("📍 Location Update — Lat: \(lat), Lng: \(lng), Speed: \(speed), Time: \(recordedAt)")
        }
    }

    // 🛑 Called when there's an error receiving updates
    func didFailWithError(_ error: Error) {
        print("🚫 Location error: \(error.message)")
    }
}

Roam will keep delivering updates automatically in both foreground and background (depending on permission level and mode).

✅ What You Should See After a Successful Setup
  • After calling Roam.startTracking(...), didUpdateLocation(_:) will be triggered with new location data

  • You’ll see values for latitude, longitude, speed, and other metadata

  • If anything goes wrong, didFailWithError(_:) will log details

🧪 Test Tip:

Simulate location changes using:

  • Xcode > Debug > Simulate Location

  • A physical device while moving

  • A pre-recorded GPX file

Watch the Xcode console for printed updates from didUpdateLocation.

Step 6: Enable and Configure Batch Sync

By default, the Roam SDK sends each location update in real-time. However, you can enable Batch Mode to buffer and transmit multiple location events together. This helps reduce network usage and battery drain — especially when the device is offline or in low-connectivity environments.

6.1 Enable Batch Transmission

In your AppDelegate or wherever you initialize the SDK, enable batch syncing with the following setup:

import RoamBatchConnector

// Initialize the batch connector
RoamBatch.shared.initialize()

// Create a batch publish config
let batchPublish = RoamBatchPublish()
batchPublish.enableAll() // Sends all available fields

// Apply batch config
let syncEnabled = true
let syncInterval: NSNumber? = 1 // Sync every 1 hour (range: 1–24). Set nil for default behavior

RoamBatch.shared.setConfig(enable: syncEnabled, syncHour: syncInterval, publish: batchPublish)

You can call setConfig(...) anywhere after SDK initialization, such as after user login or when the app is active.

6.2 Customize What Gets Sent (Optional)

If you don’t want to send everything, you can manually select what data should be included:

let batchPublish = RoamBatchPublish()
batchPublish.userId = true
batchPublish.latitude = true
batchPublish.longitude = true
batchPublish.speed = true
batchPublish.appVersion = true
batchPublish.deviceModel = true
batchPublish.batteryStatus = true

RoamBatch.shared.setConfig(enable: true, publish: batchPublish)

All fields are optional — just toggle the ones your use case requires. See full field list in the Data Enrichment section.

Disabling Batch Sync

To stop batching and return to real-time updates:

RoamBatch.shared.setConfig(enable: false, publish: RoamBatchPublish())

This will stop buffering and resume real-time location updates.

✅ What You Should See After a Successful Setup
  • Location updates will continue, but now they’ll be sent in batches instead of individually.

  • Reduced network calls in background or poor-connectivity conditions.

  • Improved battery usage for long-running location sessions.

🧪 Test Tip: Simulate offline behavior by disabling Wi-Fi and mobile data. Then re-enable them after some time to observe batch sync behavior.

Data Included in Batch Location Updates

When Batch Sync is enabled, the Roam SDK includes a wide range of contextual metadata with each location update. This allows for more accurate analytics and deeper insights into user behavior, device state, and environmental conditions.

Below is the full list of fields that can be optionally included in each batched update. You can control which of these fields to include using the RoamBatchPublish configuration.

#
Field Name
Parameter Key

1

Tracking Mode

tracking_mode

2

Latitude

latitude

3

Longitude

longitude

4

Speed

speed

5

Altitude

altitude

6

Course

course

7

Horizontal Accuracy

horizontal_accuracy

8

Vertical Accuracy

vertical_accuracy

9

Activity

activity

10

App Context

app_context

11

Recorded At

recorded_at

12

Timezone Offset

tz_offset

13

Battery Status

battery_status

14

Battery Remaining (%)

battery_remaining

15

Battery Saver

battery_saver

16

Network Status

network_status

17

Network Type

network_type

18

Network State

network_state

19

Location Permission

location_permission

20

GPS Status

gps_status

21

Device Model

device_model

22

Device Manufacturer

device_manufacturer

23

Device Name

device_name

24

Kernel Version

kernel_version

25

IP Address

ip_address

26

Public IP Address

public_ip_address

27

Wi-Fi SSID

wifi_ssid

28

Locale Country

locale_country

29

Locale Language

locale_language

30

Carrier Name

carrier_name

31

App Name

app_name

32

App Installation Date

app_installation_date

33

App Version

app_version

34

System Name

system_name

35

Centroid

centroid

36

Custom Metadata (Bundle)

metadata

37

SDK Version

sdk_version

38

Location ID

location_id

39

User ID

user_id

40

App ID

app_id

41

Local Geofence Event

local_geofence_events

42

Android SDK Version

android_sdk_version

43

Android Release Version

android_release_version

44

Build Type

build_type

45

Build Version Incremental

build_version_incremental

46

Build ID

build_id

47

AAID (Android)

aaid

48

Package Name

package_name

49

Installed Applications

installed_applications

50

Allow Mocked Locations

allow_mocked

51

OS Version

os_version

52

IDFV (iOS)

idfv

53

IDFA (iOS)

idfa

54

Source

source

55

Bundle ID

bundle_id

56

Location Listener

location_listener

57

Location Authorization Status

location_authorization_status

58

Nearby Events

nearby_events

59

App Details

app_details

60

Geofence Events

geofence_events

61

Trips Events

trips_events

62

Location Events

location_events

63

Events Listener

event_listener

64

Airplane Mode

airplane_mode

65

Discarded Flag

discarded

🎉 You’re All Set!

You’ve successfully completed the full Roam iOS SDK integration — from installing and initializing the SDK, to requesting permissions, starting location tracking, and enabling optional batch sync.

Your app is now ready to:

  • Continuously track user location with battery-efficient background support

  • Receive real-time updates through RoamDelegate callbacks

  • Sync location data to Roam servers in batches, if enabled

If you’ve followed each step and are seeing location updates in your Xcode logs, your integration is working correctly.

Need help? Check out our FAQs, explore the , or contact our support team.

Roam Dashboard
Getting Started
sample project on GitHub