iOS SDK - Advanced Options


JavaScript Interface for Hybrid Apps

Overview

Enable Singular SDK functionality from JavaScript code in WKWebView-based hybrid apps using the JavaScript interface.

Supported Methods:

  • setCustomUserId: Set custom user identifier
  • unsetCustomUserId: Remove custom user identifier
  • event: Track events with or without attributes
  • revenue: Track revenue

Setup WKWebView Integration

Configure the JavaScript interface in your view controller's WKNavigationDelegate to enable Singular SDK methods from JavaScript.

Note: Starting in iOS 8.0+ Apple recommends using WKWebView to add web content to your app. Do not use UIWebView or WebView. See Apple's WKWebView documentation for more information.

SwiftObjective-C
import UIKit
import WebKit

class ViewController: UIViewController {
    
    var webView: WKWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Create WKWebView
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.navigationDelegate = self
        view.addSubview(webView)
        
        // Load web content
        if let url = Bundle.main.url(forResource: "index", withExtension: "html") {
            webView.loadFileURL(url, allowingReadAccessTo: url)
        }
    }
}

extension ViewController: WKNavigationDelegate {
    
    func webView(_ webView: WKWebView,
                decidePolicyFor navigationAction: WKNavigationAction,
                decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        // Check if Singular JavaScript interface exists
        let js = "typeof(Singular)"
        webView.evaluateJavaScript(js) { (result, error) -> Void in
            if let resultString = result as? String {
                if resultString == "undefined" {
                    // Load Singular JavaScript interface
                    do {
                        if let path = Bundle.main.path(forResource: "Singular", ofType: "js") {
                            let contents = try String(contentsOfFile: path)
                            webView.evaluateJavaScript(contents, completionHandler: nil)
                        }
                    } catch {
                        print("Error loading Singular.js: \(error)")
                    }
                } else {
                    // Process Singular SDK request
                    Singular.processJSRequestWK(webView, withURL: navigationAction.request)
                }
            }
        }
        
        // Allow navigation
        decisionHandler(.allow)
    }
}

Setup Requirements:

  • Include the Singular.js file in your app bundle
  • Set your view controller as the WKWebView's navigation delegate
  • Implement the decidePolicyForNavigationAction delegate method
  • Call processJSRequestWK to handle Singular SDK requests

JavaScript Usage

Call Singular methods from JavaScript code running in your WKWebView.

Track Events

JavaScript
// Simple event without attributes
Singular.event('level_completed');

// Event with attributes (pass as JSON string)
Singular.event('purchase_attempt', 
    JSON.stringify({
        "item_name": "sword",
        "item_category": "weapons",
        "item_price": 9.99
    })
);

Track Revenue

JavaScript
// Track revenue in USD
Singular.revenue('USD', 9.99);

// Track revenue in other currencies
Singular.revenue('EUR', 8.50);

Manage Custom User ID

JavaScript
// Set custom user ID
Singular.setCustomUserId('user_12345');

// Remove custom user ID
Singular.unsetCustomUserId();

JavaScript API Notes:

  • All methods are called on the global Singular object
  • Event attributes must be passed as JSON-stringified objects
  • Method names use camelCase (e.g., setCustomUserId)
  • The interface automatically bridges JavaScript calls to native SDK methods