CMSCure logo

Getting Started

Welcome to CMSCure, your one-click content delivery system designed to eliminate the friction between content updates and your live applications across all platforms.

Tired of the endless cycle of code changes, builds, reviews, and deployments just to tweak a label, update a banner image, or change a button color? CMSCure empowers your entire team – developers, designers, product managers, and marketers – to manage and publish content updates instantly.

Integrate our lightweight SDK into your iOS, Android, React Native, Flutter, Unity, or Web application. Define your content keys and structure in our intuitive dashboard. Then, update text, colors, images, numbers, boolean flags, and more whenever you need to, and see the changes reflect in your live app within seconds.

This documentation provides everything you need to get started, understand the core principles, and integrate CMSCure into your specific platform.

Conceptual Workflow

Here's the typical flow for using CMSCure:

1.  **Dashboard Setup:**
    * Define 'Tabs' (e.g., `login_screen`, `settings`, `product_details`). These are logical groups for your content.
    * Define 'Keys' within each Tab (e.g., `login_button_text`, `welcome_message`, `primary_color`). These are unique identifiers for individual content pieces.
    * Add translations and values for each Key across different languages.
    * Publish your changes from the dashboard.

2.  **SDK Integration (Example for iOS with Swift Package Manager):**
    * Install the CMSCure SDK for your platform (e.g., iOS via SPM, Android via Gradle).
    * **Initialize & Configure the SDK early in your app's lifecycle:**
      ```swift
      // In your AppDelegate or App struct (SwiftUI)
      import CMSCureSDK
      
      Cure.shared.configure(
          projectId: "YOUR_PROJECT_ID",
          apiKey: "YOUR_API_KEY",
          projectSecret: "YOUR_PROJECT_SECRET"
          // Optional: serverUrlString: "https://custom.server.com",
          // Optional: socketIOURLString: "wss://custom.socket.com"
      )
      Cure.shared.debugLogsEnabled = true // For development
      ```
    * Provide your Project ID, API Key, and Project Secret. The API Key is used for request authentication, and the Project Secret is used for legacy encryption/handshake processes.

3.  **Fetch & Display Content:**
    * **SwiftUI (iOS):** Use provided property wrappers like `@StateObject var myText = CureString("key", tab: "tab")` or the `"key".cure(tab: "tab")` extension.
    * **Other Platforms:** Utilize similar reactive wrappers, hooks, or manual fetch methods provided by the respective SDK (e.g., `CMSCure.instance.getTranslation("key", "tab")`).
    * The SDK handles caching and fetching the latest content automatically.

4.  **Real-time Updates:**
    * When you publish changes in the CMSCure dashboard, the SDK (if connected via WebSocket) receives updates.
    * UI components linked to CMSCure (like SwiftUI's `CureString`) update automatically. For manually fetched content, you might need to listen to update notifications or re-fetch.

5.  **Instant Deployment of Content:**
    * Text, color, and image URL changes are live in your app within seconds of publishing from the dashboard, without requiring a new app build or store submission.

Core Concepts

Understanding these concepts is key to leveraging CMSCure effectively:

  • Tabs: Logical containers for your content, often mapping to app screens or features (e.g., "login_screen", "user_profile", "settings_ui"). You define these in the CMSCure dashboard. The special tab "__colors__" is typically used for global color definitions.
  • Keys: Unique identifiers within a Tab for specific content elements like text strings, color hex codes, image URLs, boolean flags, or numbers (e.g., "welcome_message", "primary_brand_color", "hero_image_url", "show_feature_x").
  • Values & Translations: Each Key holds values for different languages. The SDK automatically retrieves the value for the currently active language (set via a method like Cure.shared.setLanguage(...)).
  • SDK Configuration: Each platform SDK must be initialized once with your Project ID, API Key, and Project Secret. The API Key authenticates requests, while the Project Secret is used for specific operations like legacy encryption or handshake validation.
  • Real-time Sync: Utilizes WebSockets to instantly push updates from the dashboard to connected apps. SDKs often provide reactive UI components or hooks (like SwiftUI's CureString) that update automatically.
  • Intelligent Caching: Fetched content is cached on-device for offline availability and performance. The cache is automatically updated when changes are detected.
  • End-to-End Security (Legacy): For SDKs/endpoints using it, legacy data transfers might involve AES-GCM encryption for request/response bodies and HMAC-SHA256 for request signing, with keys derived from the Project Secret. Modern flows primarily rely on API Key authentication over HTTPS/WSS.

General SDK Pseudocode

// --- Initialization & Configuration (Early in App Lifecycle) ---
// This is a conceptual representation. Syntax varies by platform.

// Example: Swift (iOS)
// Cure.shared.configure(
//     projectId: "YOUR_PROJECT_ID",
//     apiKey: "YOUR_API_KEY",
//     projectSecret: "YOUR_PROJECT_SECRET" 
// )
// Cure.shared.debugLogsEnabled = true
// Cure.shared.setLanguage("en") // Set initial language

// General Concept:
CMSCureSDK.configure(
    projectId: "YOUR_PROJECT_ID",          // Unique ID for your project
    apiKey: "YOUR_API_KEY",                // For authenticating API requests
    projectSecret: "YOUR_PROJECT_SECRET",  // For encryption/handshake
    enableAutoRealTimeUpdates: true         // Optional: turn off for manual control
)
  .then(() => {
    print("SDK Configured & Authenticated (if auth is part of configure)")
    CMSCureSDK.setLanguage("en") // Set initial language
  })
  .catch((error) => {
    print("SDK Configuration/Authentication Failed: ", error)
  })


// --- Fetching Content (Inside your UI code) ---
// Platform-specific methods or reactive wrappers are used.

// Example: Swift (using SwiftUI reactive wrappers)
// @StateObject var welcomeText = CureString("welcome_title", tab: "home_screen")
// @StateObject var primaryColor = CureColor("primary_button_bg")
// Text(welcomeText.value)
// Button("Submit") { /* ... */ }.background(primaryColor.value ?? .blue)

// General Concept (manual fetch):
let welcomeMessage = CMSCureSDK.translation(forKey: "welcome_title", inTab: "home_screen", defaultValue: "Welcome!")
let buttonBgColorHex = CMSCureSDK.colorValue(forKey: "button_background", defaultValue: "#007AFF")
// let promoImageURL = CMSCureSDK.imageUrl(forKey: "promo_banner", inTab: "home_assets")
// let shouldShowFeature = CMSCureSDK.boolValue(forKey: "enable_feature_x", inTab: "settings", defaultValue: false)
// let maxItems = CMSCureSDK.numberValue(forKey: "max_cart_items", inTab: "config", defaultValue: 10)


// --- Displaying Content ---
// Bind the fetched values or reactive properties to your UI elements.
// Label.text = welcomeMessage
// Button.backgroundColor = parseColor(buttonBgColorHex) // Convert hex if needed
// PromoBanner.visibility = shouldShowFeature


// --- Language Switching ---
CMSCureSDK.setLanguage("fr")
  .then(() => {
     print("Language changed to French")
     // UI elements using CMSCure reactive wrappers should update automatically.
     // Manually re-fetch content or update UI if not using reactive components.
  })
  .catch((error) => {
     print("Error setting language: ", error)
  })


// --- Real-time Updates ---
// SDKs typically handle this internally. Reactive wrappers/hooks update UI automatically.
// For manual handling, you might subscribe to an update event:
CMSCureSDK.onContentUpdated((updatedTabInfo) => {
  print("Content updated for tab: ", updatedTabInfo.tabName)
  // If (updatedTabInfo.tabName == "relevant_tab_for_this_view" || updatedTabInfo.tabName == "__ALL__") {
  //   RefreshManuallyFetchedData()
  // }
})

iOS SDK

Native iOS SDK for SwiftUI and UIKit applications. Manage all your app content, colors, images, and data from your CMSCure Dashboard with automatic real-time updates across all Apple platforms.

🚀 NEW: Zero-Setup Real-time Updates!

All core methods now automatically enable real-time updates with zero configuration. Just call translation(), colorValue(), imageURL(), or dataStoreRecords() and your content stays live!

Native iOSSwiftUI ReadyUIKit Compatible🚀 Auto Real-time

1. Installation (Swift Package Manager)

Add the SDK to your Xcode project using its GitHub repository URL:

  1. In Xcode: Navigate to File > Add Packages...
  2. Enter the repository URL:
    https://github.com/cmscure/ios-sdk.git
  3. Select "Up to Next Major Version" for the dependency rule.
  4. Click "Add Package". The SDK and its required dependencies (like Kingfisher for image caching) will be added to your project automatically.

2. Project Setup

Get your credentials from your CMSCure Dashboard and configure the SDK when your app launches. Real-time updates are enabled by default - no additional setup required!

🚀 Quick Setup: Find your Project ID and API Key in your project settings at app.cmscure.com

import CMSCureSDK

@main
struct YourApp: App {
    init() {
        // ✨ Real-time updates enabled by default!
        Cure.shared.configure(
            projectId: "YOUR_PROJECT_ID",
            apiKey: "YOUR_API_KEY",
            projectSecret: "YOUR_PROJECT_SECRET"
            // enableAutoRealTimeUpdates: true (default)
        )
    }
    //...
}

🚀 Revolutionary Improvement: Before vs After

😓 BEFORE: Manual Setup Required

• Manual NotificationCenter observers

• Custom subscription management

• Complex real-time setup

• Memory leak risks

• Multiple lines of boilerplate

// OLD WAY - Complex setup!
NotificationCenter.default.addObserver(...)
// Subscribe manually
// Handle cleanup in deinit
// Risk memory leaks

🎉 NOW: Zero-Setup Magic!

• Automatic real-time subscriptions

• Zero configuration needed

• Just call the methods!

• Memory-safe auto-cleanup

• One line = real-time updates

// NEW WAY - Just use it! ✨
text = Cure.shared.translation(...)
// That's it! Real-time included! 🚀
// Auto-cleanup handled for you
// Zero boilerplate needed!

Bottom Line: What used to take 10+ lines of setup now happens automatically with zero configuration!

3. SwiftUI Usage (Recommended) 🚀

For SwiftUI, the SDK provides ObservableObject wrappers that automatically update your UI when content changes in the CMS. Zero setup required for real-time updates!

  • Text & Colors: Use @StateObject var myText = CureString("key", tab: "...") and CureColor("key"). ⚡ Auto real-time!
  • Images: Drop in Cure.ManagedImage(key: "...", defaultImageName: "...") to get an auto-cached, real-time CMS image with an optional local fallback asset. Under the hood it uses Kingfisher + the SDK cache. ⚡ Auto real-time!
  • Data Stores: Use @StateObject var store = CureDataStore(apiIdentifier: "...") to get a live-updating array of your structured content. ⚡ Auto real-time!

4. UIKit & Manual Access 🚀

For UIKit or other architectures, you can fetch content directly. NEW: All core methods now automatically enable real-time updates - no manual notification subscriptions needed! Just call translation(), colorValue(), imageURL(), or dataStoreRecords() and your content stays live. In SwiftUI, drop in Cure.ManagedImage for auto-cached CMS images with optional local fallbacks. For UIKit, keep using Kingfisher’s .kf extensions to display the URLs you fetch.

⚡ Before: Manual NotificationCenter subscriptions required
🚀 Now: Just call the method - real-time updates happen automatically!

iOS SDK Usage Example

1import SwiftUI
2import CMSCureSDK
3
4// --- 1. App Initialization & SDK Configuration ---
5@main
6struct YourAppNameApp: App {
7    init() {
8        // ✨ Real-time updates enabled by default! 
9        Cure.shared.configure(
10            projectId: "YOUR_PROJECT_ID",
11            apiKey: "YOUR_API_KEY",
12            projectSecret: "YOUR_PROJECT_SECRET"
13            // enableAutoRealTimeUpdates: true (default)
14        )
15    }
16    var body: some Scene {
17        WindowGroup {
18            ContentView()
19        }
20    }
21}
22
23// --- 2. Automatic Translation with Real-time Updates ---
24struct ContentView: View {
25    @State private var appName = ""
26    @State private var welcomeMessage = ""
27    
28    var body: some View {
29        NavigationStack {
30            ScrollView {
31                VStack(spacing: 24) {
32                    VStack(spacing: 12) {
33                        Text(appName)
34                            .font(.largeTitle)
35                        Text(welcomeMessage)
36                            .font(.title3)
37                            .foregroundStyle(.secondary)
38                        // 🖼️ Auto-cached global image with local fallback asset
39                        Cure.ManagedImage(
40                            key: "dashboard_logo",
41                            contentMode: .fit,
42                            defaultImageName: "AppLogo"
43                        )
44                        .frame(width: 160, height: 64)
45                        .shadow(radius: 8)
46                    }
47                    .padding(.horizontal)
48                    
49                    ProductsList()
50                        .frame(maxHeight: 320)
51                }
52                .padding(.vertical)
53            }
54            .navigationTitle("Dashboard")
55        }
56        .onAppear {
57            // 🚀 Just call once - automatic real-time updates included!
58            appName = Cure.shared.translation(
59                forKey: "app_name",
60                screenName: "home"
61                // Real-time updates automatically enabled ✨
62            )
63            
64            welcomeMessage = Cure.shared.translation(
65                forKey: "welcome_message", 
66                screenName: "home"
67                // No manual subscriptions needed! 🎉
68            )
69        }
70    }
71}
72
73struct ProductsList: View {
74    @StateObject private var store = CureDataStore(apiIdentifier: "products")
75
76    var body: some View {
77        List {
78            ForEach(store.records) { product in
79                VStack(alignment: .leading, spacing: 4) {
80                    Text(product.string("title") ?? "Unnamed Product")
81                        .font(.headline)
82                    if let price = product.double("price") {
83                        Text(price, format: .currency(code: "USD"))
84                            .font(.subheadline)
85                            .foregroundStyle(.secondary)
86                    }
87                    if let summary = product.string("description") {
88                        Text(summary)
89                            .font(.footnote)
90                            .foregroundStyle(.secondary)
91                    }
92                }
93                .padding(.vertical, 6)
94            }
95            .listRowBackground(Color.clear)
96        }
97        .listStyle(.plain)
98    }
99}
100
101
102// --- 3. UIKit with Automatic Real-time Updates ---
103import UIKit
104import Kingfisher // For powerful image caching
105
106class MyViewController: UIViewController {
107    @IBOutlet weak var titleLabel: UILabel!
108    @IBOutlet weak var heroImageView: UIImageView!
109    private var productRecords: [CureDataStoreRecord] = []
110
111    override func viewDidLoad() {
112        super.viewDidLoad()
113        updateContentFromCMS()
114        
115        // 🚀 ENHANCED: Real-time updates now happen automatically!
116        // No manual NotificationCenter observers needed anymore ✨
117        // Just call the methods and they auto-subscribe for updates!
118    }
119
120    func updateContentFromCMS() {
121        // 📱 Auto real-time translation - no manual subscriptions!
122        titleLabel.text = Cure.shared.translation(for: "vc_title", inTab: "uikit_screen")
123        loadProducts()
124        
125        // 🖼️ Auto real-time images with Kingfisher caching
126        if let imageUrl = Cure.shared.imageURL(forKey: "vc_hero_image") {
127            heroImageView.kf.setImage(with: imageUrl)
128            // Updates automatically when image changes in CMS! 🎉
129        }
130    }
131
132    private func loadProducts() {
133        productRecords = Cure.shared.dataStoreRecords(for: "products")
134        productRecords.forEach { record in
135            print("Product:", record.string("title") ?? "nil")
136            print("Description:", record.string("description") ?? "nil")
137        }
138    }
139
140    // 🎯 Optional: Keep this for custom logic, but auto-updates handle the basics
141    @objc func cmsContentDidUpdate() {
142        // This still works for custom refresh logic
143        self.updateContentFromCMS()
144    }
145    
146    // No more manual observer cleanup needed! SDK handles it automatically 🚀
147}
148

🚀 The Future of iOS CMS Integration is Here

No more complex setups, no more manual subscriptions, no more boilerplate code. Just call one method and get automatic real-time updates that work like magic.

100% backward compatibleZero breaking changesInstant upgrade benefits

JavaScript SDK

The official CMSCure JavaScript SDK enables seamless integration of dynamic content management, multi-language support, and content updates into your web applications. Compatible with React, Next.js, Vue, Angular, Svelte, and vanilla JavaScript.

Official SDKProduction ReadyTypeScript

1. Installation

Install the official CMSCure SDK from NPM:

# Using npm
npm install @cmscure/javascript-sdk

# Using Yarn
yarn add @cmscure/javascript-sdk

# Using pnpm
pnpm add @cmscure/javascript-sdk

Or include directly via CDN for vanilla HTML/JS projects:

<script src="https://cdn.jsdelivr.net/npm/@cmscure/javascript-sdk@latest/dist/cmscure.umd.min.js"></script>

2. Project Setup

Get your credentials from your CMSCure Dashboard and initialize the SDK in your application's entry point.

3. Key Features

  • Translations: translation(key) - Multi-language content management
  • Colors: color(name) - Dynamic theme and branding colors
  • Images: image(key) - Optimized image delivery via CDN
  • Data Stores: dataStore(name) - Custom structured data for dynamic content

4. Multi-Language Support

Built-in internationalization with automatic language detection and easy language switching.

  • Language Detection: Automatic browser language detection with fallback support
  • Dynamic Switching: setLanguage(code) - Change language at runtime
  • Language Management: getAvailableLanguages() - Get configured languages
  • Content Updates: Content automatically updates when language changes

Manage all your application content from the CMSCure Dashboard with dynamic content updates to your live application.

5. Performance & Reliability

Built for production applications with optimized content delivery and robust error handling.

  • CDN Integration: Fast content delivery via gateway.cmscure.com
  • Fallback Support: Graceful degradation with default values when content is unavailable
  • Caching: Intelligent content caching for improved performance
  • Error Handling: Built-in error handling and logging for production environments

Perfect for production websites, mobile apps, and applications that require reliable content management.

Ready to get started?

Create your free CMSCure account and start managing dynamic content in minutes.

Framework Integration Examples

# Install via npm
npm install @cmscure/javascript-sdk

# Or via yarn  yarn add @cmscure/javascript-sdk

# Or via CDN (no installation needed)
# Add to your HTML: <script src="https://cdn.jsdelivr.net/npm/@cmscure/javascript-sdk@latest/dist/cmscure.umd.min.js"></script>

API Reference

This section provides detailed API references for all CMSCure SDKs. While method signatures vary by platform, the core concepts of tabs, keys, and real-time updates remain consistent across all implementations.

JavaScript SDK API (@cmscure/javascript-sdk)

The JavaScript SDK provides a modern, Promise-based API for web applications. Compatible with vanilla JavaScript, React, Next.js, Vue, Angular, and other frameworks.

✨ New in v1.3.5

  • Instant cached loading - All methods return cached data immediately for faster UI updates
  • Enhanced localStorage - Persistent caching across browser sessions
  • Improved colors API - Dedicated endpoint for better performance
  • Real-time sync - Live updates with Socket.IO when project secret is provided
// Installation
npm install @cmscure/javascript-sdk

// Usage
import CMSCureSDK from '@cmscure/javascript-sdk';
const cure = new CMSCureSDK();

Configuration

await cure.configure({ projectId, apiKey })

Configures and initializes the SDK with your project credentials from app.cmscure.com. Must be called once before using other methods.

Parameters:
  • projectId (string): Your unique Project ID from the CMSCure dashboard.
  • apiKey (string): Your API Key for authenticating requests.
Returns:

Promise<void> - Resolves when configuration is complete.

Content Access Methods

cure.translation(key, tab)

Retrieves a localized string for the specified key and tab in the current language. Returns cached value immediately or null if not available.

Parameters:
  • key (string): The key for the desired string (e.g., 'welcome_message').
  • tab (string): The tab/screen name where the key is located (e.g., 'homepage').
Returns:

string | null - The localized string or null if not found.

cure.color(key)

Retrieves a color hex value for the specified global color key. Returns cached value immediately or null if not available.

Parameters:
  • key (string): The key for the desired color (e.g., 'primary_color').
Returns:

string | null - The color hex value (e.g., '#3b82f6') or null if not found.

cure.image(key)

Retrieves an optimized image URL from the CMSCure CDN for the specified image key. Returns cached URL immediately or null if not available.

Parameters:
  • key (string): The key for the desired image (e.g., 'hero_banner').
Returns:

string | null - The CDN-optimized image URL or null if not found.

cure.dataStore(apiIdentifier)

Retrieves structured data from a Data Store configured in your CMSCure dashboard. Returns cached data immediately or empty array if not available.

Parameters:
  • apiIdentifier (string): The API identifier of the Data Store.
Returns:

Array - Array of data store items with structured content.

Language Management

await cure.setLanguage(languageCode)

Changes the current language and triggers content updates across the application.

Parameters:
  • languageCode (string): Language code (e.g., 'en', 'fr', 'es').
Returns:

Promise<void> - Resolves when language change is complete.

cure.getCurrentLanguage()

Gets the currently active language code.

Returns:

string - Current language code.

await cure.getAvailableLanguages()

Retrieves all language codes configured in your CMSCure project.

Returns:

Promise<Array<string>> - Array of available language codes.

Real-time Updates

cure.onContentUpdate(callback)

Registers a callback function to be called when content is updated in real-time from the CMSCure dashboard.

Parameters:
  • callback (function): Function to call when content updates. Receives update details as parameter.
Returns:

function - Unsubscribe function to remove the listener.

cure.isConnected()

Checks if the WebSocket connection to app.cmscure.com is currently active.

Returns:

boolean - True if connected, false otherwise.

Synchronization

await cure.syncContent()

Manually triggers a full content synchronization with the CMSCure servers.

Returns:

Promise<void> - Resolves when synchronization is complete.

cure.clearCache()

Clears all cached content data, forcing fresh retrieval on next access.

Returns:

void

💡 Framework Integration: The JavaScript SDK works seamlessly with popular frameworks. Check the JavaScript SDK documentation section for React hooks, Vue composables, and other framework-specific helpers.

CMSCureSDK / Cure (Singleton)

The main entry point for interacting with the SDK. Access its functionalities via the shared singleton instance. A typealias `Cure` is provided for convenience: public typealias Cure = CMSCureSDK.

// Accessing the shared instance:
CMSCureSDK.shared
// or using the typealias:
Cure.shared

Configuration

// Swift / Android
configure(projectId: String, apiKey: String, projectSecret: String, serverUrlString: String = "https://app.cmscure.com", socketIOURLString: String = "wss://app.cmscure.com")

Configures the SDK with your project credentials and server details. This MUST be called once, early in your application's lifecycle (e.g., in AppDelegate or App struct initializer). It triggers internal setup, including legacy authentication and socket connection attempts.

Parameters:
  • projectId (String): Your unique Project ID from the CMSCure dashboard.
  • apiKey (String): Your API Key for authenticating API requests.
  • projectSecret (String): Your Project Secret, used for legacy encryption and socket handshake.
  • serverUrlString (String): Optional. Base URL for the CMSCure API. Defaults to 'https://app.cmscure.com'.
  • socketIOURLString (String): Optional. URL for the CMSCure Socket.IO server. Defaults to 'wss://app.cmscure.com'.
// Swift / Android
var debugLogsEnabled: Bool { get set }

Controls whether detailed SDK diagnostic messages are printed to the console. Defaults to true. Set to false for production builds.

// Swift / Android
var pollingInterval: TimeInterval { get set }

The interval (in seconds) at which the SDK periodically polls for content updates if socket connection is unavailable or as a fallback. Defaults to 300 seconds (5 minutes). Min: 60s, Max: 600s.

Language Management

// Swift / Android
setLanguage(_ language: String, force: Bool = false, completion: (() -> Void)? = nil)

Sets the current active language for retrieving translations. Persists the preference and triggers content updates for the new language.

Parameters:
  • language (String): The language code to set (e.g., "en", "fr").
  • force (Bool): Optional. If true, forces updates even if the language is unchanged. Defaults to false.
  • completion ((() -> Void)?): Optional. A closure called after all tabs have attempted to sync for the new language.
// Swift / Android
getLanguage() -> String

Retrieves the currently active language code.

Returns:

The current language code (e.g., "en").

// Swift / Android
availableLanguages(completion: @escaping ([String]) -> Void)

Asynchronously fetches the list of available language codes from the backend. Falls back to languages inferred from the local cache if the server request fails.

Parameters:
  • completion (([String]) -> Void): A closure called with an array of language code strings.

Content Accessors

// Swift / Android
translation(for key: String, inTab screenName: String) -> String

Retrieves a translation for a specific key within a given tab (screen name), using the currently set language. Returns an empty string if the translation is not found in the cache.

Parameters:
  • key (String): The key for the desired translation.
  • screenName (String): The name of the tab/screen where the translation key is located.
Returns:

The translated string for the current language, or an empty string if not found.

// Swift / Android
colorValue(for key: String) -> String?

Retrieves a color hex string for a given global color key. Colors are typically stored in a special tab named `__colors__`. Returns nil if the color key is not found.

Parameters:
  • key (String): The key for the desired color (e.g., "primary_brand_color").
Returns:

The color hex string (e.g., "#RRGGBB") or nil if not found.

// Swift / Android
imageUrl(for key: String, inTab screenName: String) -> URL?

Retrieves a URL for an image associated with a given key and tab, in the current language. The underlying translation for the key is expected to be a valid URL string. Returns nil if not found, empty, or not a valid URL.

Parameters:
  • key (String): The key for the desired image URL.
  • screenName (String): The name of the tab/screen where the image URL key is located.
Returns:

A URL object if a valid URL string is found, otherwise nil.

Synchronization & Cache

// Swift / Android
sync(screenName: String, completion: @escaping (Bool) -> Void)

Manually triggers a network fetch for the latest content of a specific screen name (tab). Updates the local cache and notifies handlers upon completion.

Parameters:
  • screenName (String): The name of the tab/screen to synchronize.
  • completion ( (Bool) -> Void): A closure called with true if synchronization was successful (even if no new data), false otherwise.
// Swift / Android
isTabSynced(_ tabName: String) -> Bool

Checks if the specified tab's content exists in the local cache, indicating it has been synced at least once and has data.

Parameters:
  • tabName (String): The name of the tab/screen to check.
Returns:

True if the tab has cached content, false otherwise.

// Swift / Android
clearCache()

Clears all cached data from memory and disk, including translations, colors, known tabs list, and any persisted legacy configuration. Also resets the runtime SDK configuration, requiring `configure()` to be called again for subsequent use. Stops active socket connections and polling.

Real-time Updates (Socket.IO)

// Swift / Android
startListening()

Attempts to establish or re-establish the Socket.IO connection if the SDK is configured and necessary credentials (like projectSecret for legacy handshake) are available. Called automatically after successful configuration and when the app becomes active.

// Swift / Android
stopListening()

Explicitly disconnects the Socket.IO client and releases related resources.

// Swift / Android
isConnected() -> Bool

Returns true if the Socket.IO client is currently connected to the server, false otherwise.

Returns:

A Boolean indicating the connection status.

// Swift / Android
onTranslationsUpdated(for screenName: String, handler: @escaping ([String: String]) -> Void)

Registers a handler to be called when translations for a specific screen name (tab) are updated. The handler is called immediately with cached data upon registration and then subsequently when that tab's content changes due to sync or socket events.

Parameters:
  • screenName (String): The name of the tab/screen to observe.
  • handler (([String: String]) -> Void): A closure that receives a dictionary of key-value translations for the current language.

NotificationCenter: The SDK also posts a Notification.Name.translationsUpdated notification on the main thread when content updates. The userInfo dictionary may contain a \"screenName\": String key indicating which tab was updated (or `__ALL__`).

SwiftUI Integration

For SwiftUI applications, CMSCureSDK provides ObservableObject wrappers and convenience extensions to create reactive UIs that automatically update when content changes.

ObservableObject Wrappers

Use these with @StateObject in your SwiftUI views.

// Swift / Android
class CureString: ObservableObject { get set }

An ObservableObject that provides a reactive translated string. Initialize with a key and tab name. Access the string via its `value` property.

// Swift / Android
class CureColor: ObservableObject { get set }

An ObservableObject that provides a reactive `SwiftUI.Color?`. Initialize with a color key (from the `__colors__` tab). Access the color via its `value` property.

// Swift / Android
class CureImage: ObservableObject { get set }

An ObservableObject that provides a reactive `URL?` for an image. Initialize with a key and tab name. Access the URL via its `value` property, typically used with `AsyncImage`.

String Extension

// Swift / Android
"your_key".cure(tab: "your_tab_name") -> String

A convenience extension on `String` to directly get a translation within SwiftUI views. This also triggers view updates when the underlying translation changes.

Parameters:
  • tab (String): The name of the tab/screen where the key is located.
Returns:

The translated string.

Utilities & Error Handling

The SDK includes some utilities and defines an error enum for more robust error handling.

Color Extension (SwiftUI)

// Swift / Android
extension Color { init?(hex: String?) }

An initializer for `SwiftUI.Color` that attempts to create a color from a hexadecimal string (e.g., "#RRGGBB" or "RRGGBB").

Parameters:
  • hex (String?): The hexadecimal color string.
Returns:

A `SwiftUI.Color` instance, or `nil` if the hex string is invalid.

Error Type

// Swift / Android
public enum CMSCureSDKError: Error, LocalizedError { get set }

Defines common errors encountered by the SDK, such as configuration issues, network problems, decoding failures, or sync errors. Conforms to `LocalizedError` for user-friendly descriptions.

Refer to the SDK source code for specific error cases and their localized descriptions.

Note: This reference covers JavaScript, Swift (iOS), and Android SDK APIs. Unity, Flutter, and other platform APIs will be documented as they become available. The core concepts of tabs, keys, and real-time updates remain consistent across all platforms.

CMSCure - Headless CMS for Dynamic UI Content