iOS SDK Reference

developer

iOS SDK Reference

Comprehensive API reference for the Hood iOS SDK, including initialization, analytics, push notifications, user management, and notification extensions. Supports iOS 10+ with Apple Push Notification service (APNs) integration.


Setup & initialization

These methods are a reference for integrating the Hood SDK into your app. For full setup instructions, see iOS SDK Setup.

initialize(config:)

Initializes the Hood SDK with the provided configuration. This should be called during application startup in your AppDelegate’s didFinishLaunchingWithOptions method.

Key behaviors:

  • Must be called once during app startup
  • Configures analytics, push notifications, and other features based on builder settings
  • Automatically begins session tracking if analytics is enabled
  • Sets up notification handling and APNs registration
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    UNUserNotificationCenter.current().delegate = self
    let builder = OcambaBuilder(apiKey: "YOUR_API_KEY").push().build()
    OcambaHoood.initialize(config: builder)
    return true
}

Parameters:

  • config (Configuration): Configuration object from OcambaBuilder

OcambaBuilder

Builder class for configuring the Hood SDK before initialization. Supports method chaining for fluent configuration.

Key behaviors:

  • Chain configuration methods before calling build()
  • Each builder method returns the builder instance for method chaining
  • Configuration is finalized when build() is called
  • API key is required and validated during initialization
// Basic configuration
let config = OcambaBuilder(apiKey: "YOUR_API_KEY").build()

// Full configuration with all features
let config = OcambaBuilder(apiKey: "YOUR_API_KEY")
    .push()                           // Enable push notifications
    .analytics(true)                  // Enable analytics (default: true)
    .scheduleNotificaitons(3600)      // Schedule notifications every hour
    .customNotificationHandling()     // Enable custom notification handling
    .build()

OcambaHoood.initialize(config: config)

Parameters:

  • apiKey (String): Your Hood API key from the Ocamba platform

push()

Enables push notification functionality in the SDK.

Key behaviors:

  • Registers with APNs for push notifications
  • Handles notification display and tracking
  • Required for receiving Hood push notifications
  • Must be called before build()
let builder = OcambaBuilder(apiKey: "YOUR_API_KEY").push()

Returns:

  • OcambaBuilder: Builder instance for method chaining

analytics(_:)

Enables or disables analytics tracking.

Key behaviors:

  • Analytics is enabled by default
  • Tracks app installs, sessions, and custom events
  • Data is sent to Hood servers for campaign targeting
  • Can be disabled for privacy compliance
// Disable analytics
let builder = OcambaBuilder(apiKey: "YOUR_API_KEY").analytics(false)

// Explicitly enable analytics (default behavior)
let builder = OcambaBuilder(apiKey: "YOUR_API_KEY").analytics(true)

Parameters:

  • enabled (Bool): Set to false to disable analytics, true to enable (default: true)

Returns:

  • OcambaBuilder: Builder instance for method chaining

scheduleNotificaitons(_:)

Enables scheduled local notifications at specified intervals to increase user engagement.

Key behaviors:

  • Creates local notifications (not server-sent)
  • Uses default notification content
  • Respects system notification settings and permissions
  • Notifications continue until app is uninstalled
// Schedule notifications every hour (3600 seconds)
let builder = OcambaBuilder(apiKey: "YOUR_API_KEY")
    .scheduleNotificaitons(3600)

// Schedule daily notifications (86400 seconds)
let builder = OcambaBuilder(apiKey: "YOUR_API_KEY")
    .scheduleNotificaitons(86400)

Parameters:

  • interval (TimeInterval): Time interval in seconds between notifications

Returns:

  • OcambaBuilder: Builder instance for method chaining

customNotificationHandling()

Enables custom notification handling mode for advanced notification customization.

Key behaviors:

  • Allows custom notification presentation
  • Disables default notification handling
  • Requires manual notification display implementation
  • Used for custom notification UI and behavior
let builder = OcambaBuilder(apiKey: "YOUR_API_KEY")
    .customNotificationHandling()

Returns:

  • OcambaBuilder: Builder instance for method chaining

Push notification methods

registerToken(_:)

Registers the device token with Hood for push notifications. This should be called when the app receives a device token from APNs.

Key behaviors:

  • Must be called after receiving device token from APNs
  • Sends token to Hood servers for push targeting
  • Called automatically by the system after successful APNs registration
  • Token is persisted and refreshed automatically by the system
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    OcambaHoood.registerToken(deviceToken)
    
    // Optional: Log token for debugging
    let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    print("Device Token: \(tokenString)")
}

Parameters:

  • deviceToken (Data): Device token from APNs

pushTrackOpen(_:response:completion:)

Tracks when a user opens a push notification and handles the notification action URL.

Key behaviors:

  • Tracks notification opens for analytics and conversion tracking
  • Can handle URL automatically or return it for custom handling
  • Should be called in userNotificationCenter(_:didReceive:withCompletionHandler:)
  • Supports deep linking and custom URL schemes
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    
    // Option 1: Return URL for custom handling
    OcambaHoood.pushTrackOpen(true, response: response, completion: { url in
        if let url = url {
            // Custom URL handling
            if url.scheme == "myapp" {
                // Handle deep link
                self.handleDeepLink(url)
            } else {
                // Open in Safari
                UIApplication.shared.open(url)
            }
        }
    })
    
    // Option 2: Let SDK handle URL automatically
    OcambaHoood.pushTrackOpen(false, response: response, completion: { url in
        // SDK opens URL in browser automatically
    })
    
    completionHandler()
}

Parameters:

  • handleUrl (Bool): If true, returns URL in completion; if false, SDK opens URL automatically
  • response (UNNotificationResponse): Notification response object from user notification center
  • completion ((URL?) -> Void): Completion handler with optional URL

didReciveAdministrativeNotificationWith(_:completion:)

Handles silent administrative notifications used for configuration updates.

Key behaviors:

  • Processes silent notifications (content-available: 1)
  • Used for updating SDK configuration without user interaction
  • Does not display notification to user
  • Handles geofence and beacon updates
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    OcambaHoood.didReciveAdministrativeNotificationWith(userInfo) { (geo, bcs) in
        // geo: Geofence data (if any)
        // bcs: Beacon data (if any)
        
        if let geoData = geo {
            print("Geofence data updated: \(geoData)")
        }
        
        if let beaconData = bcs {
            print("Beacon data updated: \(beaconData)")
        }
    }
}

Parameters:

  • userInfo ([AnyHashable: Any]): Notification user info dictionary
  • completion ((Any?, Any?) -> Void): Completion handler with geofence and beacon data

Notification Service Extension

Methods for processing notifications in the Notification Service Extension to support rich media and advanced features.

didReceiveNotification(with:best:completion:)

Processes incoming notifications in the Notification Service Extension. Enables rich media attachments, notification modification, and impression tracking.

Key behaviors:

  • Called in Notification Service Extension’s didReceive(_:withContentHandler:)
  • Downloads and attaches rich media (images, videos)
  • Modifies notification content before display
  • Tracks notification impressions for analytics
import UserNotifications
import OcambaHoood

class NotificationService: UNNotificationServiceExtension {
    
    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?
    var receivedRequest: UNNotificationRequest!
    
    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        self.receivedRequest = request
        self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        if let bestAttemptContent = bestAttemptContent {
            OcambaHoood.didReceiveNotification(with: request, best: bestAttemptContent) { (content) in
                // Content now includes rich media attachments
                contentHandler(content)
            }
        }
    }
}

Parameters:

  • request (UNNotificationRequest): Notification request from system
  • bestAttemptContent (UNMutableNotificationContent): Mutable notification content to modify
  • completion ((UNNotificationContent) -> Void): Completion handler with modified content

notificationBuilderWillTerminate(with:best:completion:)

Handles notification processing when the service extension is about to be terminated by the system.

Key behaviors:

  • Called when extension time limit is reached (typically 30 seconds)
  • Provides fallback notification content
  • Ensures notification is displayed even if processing isn’t complete
  • Called in serviceExtensionTimeWillExpire()
override func serviceExtensionTimeWillExpire() {
    // System is about to terminate extension - deliver best attempt
    if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
        OcambaHoood.notificationBuilderWillTerminate(
            with: receivedRequest.content.userInfo, 
            best: bestAttemptContent
        ) { (content) in
            // Deliver final content before termination
            contentHandler(content)
        }
    }
}

Parameters:

  • userInfo ([AnyHashable: Any]): Original notification user info
  • bestAttemptContent (UNMutableNotificationContent): Best attempt content
  • completion ((UNNotificationContent) -> Void): Completion handler with final content

getNotificationContent(userInfo:)

Extracts Hood notification content from user info dictionary.

Key behaviors:

  • Parses notification payload
  • Returns structured notification data
  • Used for custom notification handling
  • Provides access to notification metadata
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    let notificationContent = OcambaHoood.getNotificationContent(userInfo: userInfo)
    
    // Access notification properties
    if let content = notificationContent {
        print("Notification received: \(content)")
    }
}

Parameters:

  • userInfo ([AnyHashable: Any]): Notification user info dictionary

Returns:

  • Notification content object

getPreferedContentSize(with:)

Calculates the preferred content size for notification content extension display.

Key behaviors:

  • Used in Notification Content Extension
  • Determines optimal size for custom notification UI
  • Supports multi-message notifications
  • Adapts to notification content
import UserNotifications
import UserNotificationsUI
import OcambaHoood

class NotificationViewController: UIViewController, UNNotificationContentExtension {
    
    func didReceive(_ notification: UNNotification) {
        // Set preferred size based on notification content
        self.preferredContentSize = OcambaHoood.getPreferedContentSize(with: notification)
        
        // Display custom notification UI
        // ...
    }
}

Parameters:

  • notification (UNNotification): Notification object

Returns:

  • CGSize: Preferred content size for notification display

Badge management

Manage notification badge counts on the app icon.

decreseNotificationCount(forNotif:)

Decreases the notification badge count by one when a notification is processed.

Key behaviors:

  • Automatically decrements badge count
  • Updates app icon badge
  • Called in Notification Service Extension
  • Prevents negative badge counts
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
    if let bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) {
        
        // Decrease badge count
        OcambaHoood.decreseNotificationCount(forNotif: bestAttemptContent)
        
        contentHandler(bestAttemptContent)
    }
}

Parameters:

  • content (UNMutableNotificationContent?): Notification content to modify

addNotificationCount(forNotif:)

Increases the notification badge count by one for new notifications.

Key behaviors:

  • Automatically increments badge count
  • Updates app icon badge
  • Called in Notification Service Extension
  • Reflects total unread notifications
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
    if let bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) {
        
        // Increase badge count
        OcambaHoood.addNotificationCount(forNotif: bestAttemptContent)
        
        contentHandler(bestAttemptContent)
    }
}

Parameters:

  • content (UNMutableNotificationContent?): Notification content to modify

Analytics & tracking

Track custom events and user behavior for analytics and campaign targeting.

track(_:)

Tracks custom events with key-value pairs. Events are queued locally and sent to the server when sendTrack() is called.

Key behaviors:

  • Events are stored locally until sendTrack() is called
  • Supports dictionaries with any value types
  • Events with empty string values are treated as deletions
  • Used for user segmentation and campaign targeting
// Track single event
OcambaHoood.track(["button_clicked": "signup"])

// Track user properties
OcambaHoood.track([
    "user_level": 5,
    "subscription": "premium",
    "last_purchase_date": "2024-01-15"
])

// Track purchase event
OcambaHoood.track([
    "product_id": "prod_123",
    "price": 29.99,
    "currency": "USD",
    "category": "electronics"
])

// Remove event from server (set empty value and send)
OcambaHoood.track(["old_property": ""])
OcambaHoood.sendTrack()

Parameters:

  • parameters ([String: Any]): Dictionary of event properties

sendTrack()

Sends all queued tracking events to the Hood server.

Key behaviors:

  • Flushes all locally stored events
  • Sends data to Hood analytics servers
  • Should be called after tracking important events
  • Automatically called on app background/termination
// Track events
OcambaHoood.track(["screen_view": "home"])
OcambaHoood.track(["feature_used": "search"])

// Send all tracked data
OcambaHoood.sendTrack()

getTrack()

Retrieves all locally stored tracking events.

Key behaviors:

  • Returns all events queued for sending
  • Events remain in storage until sent
  • Useful for debugging and verification
  • Returns dictionary of all tracked properties
let trackedEvents = OcambaHoood.getTrack()

if let events = trackedEvents {
    print("Currently tracked events: \(events)")
    // Example output: ["screen_view": "home", "user_level": 5]
}

Returns:

  • [String: Any]?: Dictionary of all tracked events

getTrackFor(key:)

Retrieves a specific tracked event value by key.

Key behaviors:

  • Returns value for specific event key
  • Returns nil if key doesn’t exist
  • Event remains in storage after retrieval
  • Useful for conditional logic based on tracked data
// Check specific tracked value
if let userLevel = OcambaHoood.getTrackFor(key: "user_level") as? Int {
    print("User level: \(userLevel)")
    
    if userLevel >= 10 {
        // Show premium features
    }
}

// Check subscription status
if let subscription = OcambaHoood.getTrackFor(key: "subscription") as? String {
    print("Subscription type: \(subscription)")
}

Parameters:

  • key (String): Event key to retrieve

Returns:

  • Any?: Event value, or nil if not found

removeTrackFor(key:)

Removes a specific tracked event from local storage.

Key behaviors:

  • Deletes event from local storage only
  • Does not affect already sent data on server
  • Event will not be included in next sendTrack()
  • To remove from server, use track() with empty string
// Remove specific event from local storage
OcambaHoood.removeTrackFor(key: "temporary_flag")

// To remove from both local and server:
OcambaHoood.track(["user_property": ""])  // Empty string marks for deletion
OcambaHoood.sendTrack()                   // Send deletion to server

Parameters:

  • key (String): Event key to remove

UTM parameters

Set and manage UTM parameters for campaign attribution and analytics.

setUtm(::)

Sets a UTM parameter for campaign tracking and attribution.

Key behaviors:

  • Used for campaign attribution
  • Supports standard UTM parameters (source, medium, campaign, term, content)
  • Parameters persist across app sessions
  • Sent with analytics data for attribution
// Track campaign parameters from deep link or app launch
OcambaHoood.setUtm("source", "google")
OcambaHoood.setUtm("medium", "cpc")
OcambaHoood.setUtm("campaign", "summer_sale_2024")
OcambaHoood.setUtm("term", "running+shoes")
OcambaHoood.setUtm("content", "banner_ad_1")

// Set custom UTM parameters
OcambaHoood.setUtm("channel", "email")
OcambaHoood.setUtm("promo_code", "SAVE20")

Parameters:

  • key (String): UTM parameter name
  • value (String): UTM parameter value

getUtm(_:)

Retrieves a UTM parameter value by key.

Key behaviors:

  • Returns stored UTM parameter
  • Returns nil if parameter doesn’t exist
  • Parameters persist until explicitly removed
  • Used for displaying attribution data
// Get campaign source
if let source = OcambaHoood.getUtm("source") {
    print("User came from: \(source)")
}

// Get campaign name
if let campaign = OcambaHoood.getUtm("campaign") {
    print("Campaign: \(campaign)")
}

// Check for promo code
if let promoCode = OcambaHoood.getUtm("promo_code") {
    // Apply promo code automatically
    applyPromoCode(promoCode)
}

Parameters:

  • key (String): UTM parameter name

Returns:

  • String?: UTM parameter value, or nil if not set

removeUtm(_:)

Removes a UTM parameter from storage.

Key behaviors:

  • Deletes UTM parameter permanently
  • Parameter will not be sent with future analytics
  • Useful for clearing one-time campaign data
  • Does not affect already sent analytics
// Remove temporary campaign parameter
OcambaHoood.removeUtm("promo_code")

// Clear all campaign parameters after conversion
OcambaHoood.removeUtm("source")
OcambaHoood.removeUtm("medium")
OcambaHoood.removeUtm("campaign")
OcambaHoood.removeUtm("term")
OcambaHoood.removeUtm("content")

Parameters:

  • key (String): UTM parameter name to remove

Delegate protocol

OcambaHooodDelegate

Protocol for receiving Hood SDK callbacks and initialization status.

Key behaviors:

  • Provides notification of SDK initialization completion
  • Optional protocol - implement only if needed
  • Called on main thread
  • Useful for coordinating SDK-dependent features
class AppDelegate: UIResponder, UIApplicationDelegate, OcambaHooodDelegate {
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        // Set delegate before initialization
        OcambaHoood.ocambaDelegate = self
        
        let builder = OcambaBuilder(apiKey: "YOUR_API_KEY").push().build()
        OcambaHoood.initialize(config: builder)
        
        return true
    }
    
    func ocambaInited(_ success: Bool) {
        if success {
            print("Hood SDK initialized successfully")
            
            // Enable features that depend on Hood SDK
            self.enablePushNotifications()
            self.startTracking()
        } else {
            print("Hood SDK initialization failed")
            
            // Handle initialization failure
            self.handleInitializationError()
        }
    }
}

ocambaInited(_:)

Called when SDK initialization completes.

Parameters:

  • success (Bool): Whether initialization was successful

ocambaDelegate

Property to set the delegate for receiving SDK callbacks.

Type:

  • OcambaHooodDelegate?

Troubleshooting

  1. SDK Initialization Failed

    • Verify API key is correct and active in Ocamba portal
    • Check internet connectivity during initialization
    • Ensure app bundle identifier matches configuration
    • Review console logs for specific error messages
  2. Push Notifications Not Working

    • Confirm APNs certificate is uploaded to Ocamba portal
    • Verify certificate matches app bundle identifier and environment (development/production)
    • Check App Groups capability is enabled
    • Ensure notification permissions are granted
    • Test on physical device (simulator has limitations)
    • Verify Firebase configuration if using FCM
  3. Rich Media Not Displaying

    • Ensure Notification Service Extension is properly configured
    • Verify App Groups capability is enabled for both main app and extension
    • Check deployment target is iOS 10 or higher
    • Confirm extension bundle identifier follows naming convention
    • Review extension logs for download errors
  4. Analytics Not Tracking

    • Ensure analytics is enabled: .analytics(true)
    • Verify sendTrack() is called after tracking events
    • Check internet connectivity
    • Review console logs for SDK errors
    • Confirm API key is valid
  5. Badge Count Not Updating

    • Verify badge methods are called in Notification Service Extension
    • Check notification content is mutable
    • Ensure App Groups are properly configured
    • Test badge increment and decrement separately

Debug Tips

  • Enable verbose logging in development builds
  • Check Xcode console for Hood SDK log messages
  • Use Notification Service Extension debugging
  • Monitor network requests in Charles Proxy or similar tools
  • Test with different iOS versions and devices
  • Verify all capabilities and entitlements are correctly configured

Need Help?

Contact support at [email protected] with:

  • Your App ID from Ocamba portal
  • iOS version and device information
  • Xcode version
  • Relevant logs or error messages from console
  • Steps to reproduce the issue
  • Screenshots if applicable