# AppFig > AppFig is a remote config, feature flag and A/B testing service for mobile apps and games. It lets a team change values in a live app (limits, prices, difficulty, timers, paywalls) without shipping an update, and target those changes by what a user actually did in the app. Key facts: - Platforms: Unity, Android, iOS, Flutter and Web (React), with open SDKs. - Rules are evaluated on the device with no network call per check; the SDK refreshes rules in the background from a CDN, and the app keeps working offline. - Behavioral targeting: rules can use event counts and sequences (for example "failed level 8 twice"), user properties and device properties, checked on the device. - Guided setup: paste an App Store or Google Play link, AppFig reads the reviews and suggests what to change, then opens one pull request that installs the SDK and makes the suggested values changeable. - Works alongside Firebase Remote Config: import an existing Remote Config and run both side by side. - Pricing: a free Lite plan for one app; the full version is $99 per app per month ($50 per app from the 11th app). Never priced per user, per fetch or per seat. - Dashboard: https://app.appfig.com · Contact: hello@appfig.com --- # AppFig Quick Start Source: https://appfig.com/docs/quick-start-guide Feature flags and remote config that evaluate rules client-side. Zero latency, maximum control. > **Prefer not to wire it by hand?** The [Guided Setup](https://appfig.com/docs/guided-setup) reads your Flutter, Unity, Android or iOS code, finds the values you can control and opens one pull request that installs the SDK. Start at [app.appfig.com/start](https://app.appfig.com/start). ## Install & Initialize ### Unity ```csharp AppFig.Init("company-id", "tenant-id", "prod", "api-key"); ``` ### React/Web ```typescript import AppFig from './AppFigReactSDK'; await AppFig.init({ companyId: 'company-id', tenantId: 'tenant-id', env: 'prod', apiKey: 'api-key' }); ``` ### iOS ```swift AppFig.shared.initialize( companyId: "company-id", tenantId: "tenant-id", environment: "prod", apiKey: "api-key" ) ``` ### Android ```kotlin AppFig.init( context = this, companyId = "company-id", tenantId = "tenant-id", env = "prod", apiKey = "api-key" ) ``` ## Log Events ### Unity ```csharp AppFig.LogEvent("level_complete"); AppFig.LogEvent("purchase", new Dictionary { { "item_id", "sword" }, { "price", "9.99" } }); ``` ### React/Web ```typescript AppFig.logEvent('button_clicked'); AppFig.logEvent('purchase', { item_id: 'sword', price: '9.99' }); ``` ### iOS ```swift AppFig.shared.logEvent(name: "level_complete") AppFig.shared.logEvent(name: "purchase", parameters: ["item_id": "sword"]) ``` ### Android ```kotlin AppFig.logEvent("level_complete") AppFig.logEvent("purchase", mapOf("item_id" to "sword")) ``` ## Check Features ### Unity ```csharp if (AppFig.IsFeatureEnabled("double_xp")) { ApplyDoubleXP(); } string maxLives = AppFig.GetFeatureValue("max_lives"); ``` ### React/Web ```typescript const showBanner = AppFig.getConfig('premium_banner'); if (showBanner === 'on') { renderBanner(); } ``` ### iOS ```swift if AppFig.shared.isFeatureEnabled("double_xp") { applyDoubleXP() } let maxLives = AppFig.shared.getFeatureValue("max_lives") ``` ### Android ```kotlin if (AppFig.isFeatureEnabled("double_xp")) { applyDoubleXP() } val maxLives = AppFig.getFeatureValue("max_lives") ``` ## Set Properties ### Unity ```csharp AppFig.SetUserProperty("tier", "premium"); AppFig.SetUserProperty("level", "15"); ``` ### React/Web ```typescript AppFig.setUserProperties({ tier: 'premium', level: '15' }); ``` ### iOS ```swift AppFig.shared.setUserProperty(key: "tier", value: "premium") AppFig.shared.setUserProperty(key: "level", value: "15") ``` ### Android ```kotlin AppFig.setUserProperty("tier", "premium") AppFig.setUserProperty("level", "15") ``` ## How It Works 1. **Define rules** in dashboard or JSON file 2. **SDK downloads** rules on launch (cached) 3. **App logs events** as users interact 4. **SDK evaluates** rules locally, instantly 5. **Features respond** to user behavior ## Example Rules ### Veteran Bonus ``` IF event "level_complete" count >= 10 THEN "veteran_bonus" = "2x" ``` ### Platform-Specific ``` IF device.platform IN ["iOS", "Android"] THEN "mobile_controls" = "on" ``` ### Country Pricing ``` IF device.country == "US" THEN "price" = "9.99" ``` ### A/B Test ``` IF user.id % 2 == 0 THEN "button_color" = "red" IF user.id % 2 == 1 THEN "button_color" = "blue" ``` ## Plans Every plan delivers your rules from the global CDN, evaluates them on the device and reaches devices within a minute. Players and publishes are unlimited, and SDK setup is identical on all plans. **Lite (free):** - 1 app, 1 seat, with dev and prod environments - 5 configs, 1 A/B test at a time - One AI setup - No credit card required An app is one game or product. Its iOS, Android and web versions share one app, one key and the same configs; when a change is for one platform only, add a platform condition to the rule. **Full ($99 per app a month, your first app included; $50 per app from the 11th):** - 500 configs and 25 A/B tests at a time, per app - 1,000 AI credits a month per app - Unlimited team, and email support from the team that builds AppFig See [pricing](https://appfig.com/#pricing). ## Supported Platforms - **Unity** - C# SDK (iOS, Android, Windows, macOS, WebGL) - **React/Web** - TypeScript SDK (all browsers) - **iOS** - Swift SDK (iPhone, iPad) - **Android** - Kotlin SDK (phones, tablets) ## Next Steps **Full Guides:** - [Android Integration](https://appfig.com/docs/android-integration) - [iOS Integration](https://appfig.com/docs/ios-integration) - [React/Web Guide](https://appfig.com/docs/react-web-guide) - [Unity Integration](https://appfig.com/docs/unity-integration) **Concepts:** - [Core Concepts](https://appfig.com/docs/concepts) - [How It Works](https://appfig.com/docs/how-it-works) **Reference:** - [Rule Schema](https://appfig.com/docs/rule-schema) - [Testing Guide](https://appfig.com/docs/testing) ## Auto-Detected Properties The SDK automatically detects and sets these properties: ``` platform "iOS", "Android", "Windows", "macOS", etc. os_version "17.0", "13", "11.0" language "English", "Japanese", "Spanish" timezone "America/Los_Angeles", "Asia/Tokyo" country "US", "JP", "GB" device_brand "Apple", "Samsung", "Google" device_model "iPhone 15", "Galaxy S23", "Pixel 8" ``` Use these in rules without any setup required. ## Common Patterns ### Feature Rollout ```csharp // Enable for users who completed onboarding Rule: IF event "onboarding_complete" count >= 1 THEN "new_feature" = "on" ``` ### Time-Limited Event ```csharp // Show holiday event based on timezone Rule: IF device.timezone IN ["America/Los_Angeles", "America/New_York"] AND event "app_open" count >= 1 THEN "holiday_event" = "on" ``` ### Premium Features ```csharp // Unlock features for premium users Rule: IF user.subscription_tier == "premium" THEN "unlimited_lives" = "on" ``` ### Progressive Unlock ```csharp // Increase lives as player progresses Rule 1: IF event "level_complete" count >= 5 THEN "max_lives" = "5" Rule 2: IF event "level_complete" count >= 10 THEN "max_lives" = "7" Rule 3: IF event "level_complete" count >= 20 THEN "max_lives" = "10" ``` ## Best Practices 1. **Cache feature values** - Don't check every frame 2. **Handle null** - Provide fallback values 3. **Log liberally** - More events = better targeting 4. **Test rules** - Verify before deploying 5. **Start on Lite** - free for 1 app and 5 configs, no credit card ## Quick Troubleshooting **Features return null?** - Check feature name spelling (case-sensitive) - Verify rules are loaded - Log events/properties first **Rules not updating?** - Wait for poll interval - Call `refreshRules()` manually - Check network connection **SDK not initialized?** - Must call init before any SDK methods - Initialize in app entry point --- **Ready to start?** Pick your platform above and follow the full integration guide. --- # Core Concepts Source: https://appfig.com/docs/concepts Understanding these four concepts will help you master AppFig in minutes. ## 1. Features **A feature is something you want to control remotely.** Features have: - A **name** (e.g., "double_xp", "max_lives", "welcome_message") - A **value** (e.g., "on", "5", "Welcome back!") ```csharp // Check if a feature is enabled (value == "on") if (AppFig.IsFeatureEnabled("double_xp")) { ApplyDoubleXP(); } // Get a feature's value string maxLives = AppFig.GetFeatureValue("max_lives"); // Returns "5" int lives = int.Parse(maxLives); ``` **Common feature types:** - **Boolean flags**: "new_ui" = "on" or "off" - **Numeric values**: "max_lives" = "5" - **Text content**: "welcome_message" = "Hello!" - **Complex data**: "pricing" = JSON object ## 2. Rules **Rules determine when a feature should activate and what value it should have.** A feature can have multiple rules. The **first matching rule** wins. ```json Feature: "veteran_bonus" Rule 1: IF user completed 50+ levels → value = "3x" Rule 2: IF user completed 10+ levels → value = "2x" (No match) → feature returns null ``` **Rule structure:** ```json { "conditions": { "events": [...], // User actions "user_properties": [...], // User attributes "device": [...] // Device/platform info }, "value": "on" // What to return if conditions match } ``` All three condition types must pass for a rule to match (AND logic between types). ## 3. Events **Events are user actions your app logs.** ```csharp // Simple event AppFig.LogEvent("level_complete"); // Event with parameters AppFig.LogEvent("purchase_made", new Dictionary { { "item", "sword" }, { "price", "4.99" } }); ``` **Rules can match based on:** - **Count**: User completed 10+ levels - **Recency**: User opened app in last 7 days - **Parameters**: User purchased items priced over $10 - **Sequence**: User did A, then B, then C (in order) **Example rule:** ```json { "conditions": { "events": { "mode": "simple", "operator": "AND", "items": [ { "key": "level_complete", "count": { "operator": ">=", "value": 10 }, "within_last_days": 7 } ] } }, "value": "on" } ``` This matches if user completed 10+ levels in the last 7 days. ## 4. Properties **Properties are attributes that describe users and devices.** ### User Properties Set by your app to describe the user: ```csharp AppFig.SetUserProperty("subscription_tier", "premium"); AppFig.SetUserProperty("account_age_days", "45"); AppFig.SetUserProperty("preferred_language", "en"); ``` **Example rule:** ```json { "conditions": { "user_properties": [ { "key": "subscription_tier", "value": { "operator": "==", "value": "premium" } } ] }, "value": "on" } ``` ### Device Properties Auto-detected by the SDK (no manual setup): ``` platform: "iOS", "Android", "Windows", etc. os_version: "15.0", "13", "11" language: "en-US", "ja", "es" country: "US", "JP", "GB" device_brand: "Apple", "Samsung", "Google" device_model: "iPhone 14", "Galaxy S23" ``` **Example rule:** ```json { "conditions": { "device": [ { "key": "platform", "value": { "operator": "in", "value": ["iOS", "Android"] } } ] }, "value": "on" } ``` This enables the feature only on mobile platforms. ## How They Work Together ``` 1. Your app logs events and sets user properties AppFig.LogEvent("level_complete") AppFig.SetUserProperty("subscription_tier", "free") 2. AppFig evaluates all rules for a feature Feature: "veteran_bonus" Rule 1: Check conditions ✓ Events: level_complete count >= 10? YES ✓ User properties: subscription_tier == "premium"? NO ✗ Rule 1 fails Rule 2: Check conditions ✓ Events: level_complete count >= 5? YES ✓ User properties: None required ✓ Device: None required ✅ Rule 2 passes! 3. First matching rule returns its value AppFig.GetFeatureValue("veteran_bonus") // Returns "1.5x" ``` ## Key Principles ### 1. Client-Side Evaluation Rules are evaluated **on your device**, not on a server. This means: - ✅ Zero latency (no network calls) - ✅ Works offline - ✅ No sensitive data sent to servers ### 2. First Match Wins When multiple rules could match, the **first one wins**. Order matters! ```json Feature: "discount" Rule 1: IF premium user → "50% off" Rule 2: IF any user → "10% off" Premium users will get 50% (Rule 1 matches first) Free users will get 10% (Rule 1 doesn't match, Rule 2 does) ``` ### 3. Null vs Empty String If no rules match, `GetFeatureValue()` returns `null` (not an empty string). ```csharp string value = AppFig.GetFeatureValue("veteran_bonus"); if (value == null) { // Feature has no matching rules } ``` ### 4. All Conditions Must Pass Within a rule, ALL condition types must pass: - Events AND - User Properties AND - Device Properties But within each type, you can use AND or OR operators. ## Next Steps - **[Quick Start Guide](https://appfig.com/docs/quick-start-guide)** - Set up your first feature - **[How It Works](https://appfig.com/docs/how-it-works)** - Deep dive into rule evaluation - **[Rule Schema Reference](https://appfig.com/docs/rule-schema)** - All operators and options ## Examples ### Example 1: Welcome Bonus for New Users ```csharp // Rule: Show welcome bonus to users who opened app < 3 times AppFig.LogEvent("app_open"); if (AppFig.IsFeatureEnabled("welcome_bonus")) { ShowWelcomeBonus(); } ``` ### Example 2: Platform-Specific UI ```csharp // Rule: Show mobile controls only on mobile // Device property "platform" is auto-detected if (AppFig.IsFeatureEnabled("mobile_controls")) { EnableTouchControls(); } ``` ### Example 3: Subscription-Based Content ```csharp // Set user property once after checking subscription AppFig.SetUserProperty("subscription_tier", "premium"); // Rule: Show premium content only to premium users if (AppFig.IsFeatureEnabled("premium_content")) { ShowPremiumLevels(); } ``` ### Example 4: Engagement-Based Unlocks ```csharp // Log events as user plays AppFig.LogEvent("level_complete"); AppFig.LogEvent("level_complete"); // ... 10 times total // Rule: Unlock hard mode after 10 level completions if (AppFig.IsFeatureEnabled("hard_mode")) { UnlockHardMode(); } ``` --- # Guided Setup Source: https://appfig.com/docs/guided-setup The guided setup takes an app from its store link to its first change without a release. Open it at [app.appfig.com/start](https://app.appfig.com/start) or from **Menu → Wizard** in the dashboard. You don't sign in up front: each step asks for access only when you click the thing that needs it. The checklist is shared by everyone in your company, so a product manager can start and a developer can finish the install. ## 1. Find your app Paste a Google Play or App Store link, or a package id. AppFig reads the public listing and the reviews and groups complaints into themes ("Paywall appears too early", "Sync loses my place"), each with how often it comes up and a quote. This needs no account. ## 2. Connect what you have Each source is useful on its own, and all three are read-only. | Source | What it adds | Access | |---|---|---| | **GitHub** | The events your app records and the values in your code that could change without a release | The AppFig GitHub App, on the repositories you choose | | **Google Analytics** | Where users drop off, users per value after a change, and A/B test results | Add AppFig's address to your property (Viewer or Editor) and type the property id, or sign in with Google | | **Firebase Remote Config** | Your parameters and their targeting rules, brought over as AppFig drafts | Read-only through Google Cloud IAM, or upload an exported template file | With the **Editor** role in Google Analytics, AppFig also registers the custom dimensions that results need (`feature`, `feature_value`, `experiment`, `variant`, and one `af_` user property per test). With **Viewer** it reads only, and the screen tells you which ones to add by hand. Nothing in Firebase or Google Analytics is ever changed. Remote Config rules that can't be expressed in AppFig are listed with the reason. ## 3. Scan your code The scan reads the repository and reports: - **Events**, marked as keeping or losing users when Google Analytics is connected - **Likely bottlenecks**, with real numbers - **Values you could control**: limits, prices, timings and switches set in code A parser finds events, Remote Config keys and constants. An AI pass then reads the likeliest files for values that aren't simple constants, and every finding is checked against the code before it is shown. Flutter, Unity, native Android (Kotlin, Java) and native iOS (Swift) are scanned and installed. React projects are scanned, not changed. Objective-C files are listed, never changed. ## 4. Install with one pull request Pick the values you want to control. AppFig prepares a pull request with every change listed and explained: - The AppFig SDK and its start-up, which waits up to one second for rules so the first values read are real - Event logging for the events rules will target - Each chosen value read from AppFig, with **today's value as the default** - Optionally, Remote Config keys your code reads, moved to AppFig - The fields of a Remote Config JSON read one by one, each as its own feature (Unity, Kotlin, Swift and Flutter). The JSON stays as it is and answers when AppFig has no value; a save file or API response parsed into the same kind of class is never touched Nothing is written to your repository until you open the pull request. A change that would leave a file parsing worse than before is dropped, and spots the installer is unsure about are left alone and listed as *found, not changed*. Merge it and release that build once. Until you publish a rule, the app behaves exactly as before. Users on older versions don't read values from AppFig, so nothing changes for them. ## 5. What to try Your problems, from the team, the reviews, your analytics and your code, each with what controls it and one action: - **Change it**: give a new value to everyone, or only to the users it's about - **Test it first**: an A/B test, decided by conversion or by revenue per user (see [Experiments](https://appfig.com/docs/experiments)) - **Code fix**: when nothing in the code controls the problem, the action says so instead of pretending Every action is saved as a draft. Publish only after the release that reads the value is live, so the first days of a test aren't empty. ### Adding a value later When an idea needs a value your app doesn't read from AppFig yet, **Add it to my app** shows the one line that reads it, for Flutter, Unity, Android, iOS and the web, with today's value as the default. The same screen opens from **Add to code** next to a feature's name in Features, and from an AI Agent answer that needs code. With GitHub connected and the value found by the scan, AppFig prepares a pull request instead: - **AppFig is in the app**: only that value changes, and it joins the values the app already reads - **An AppFig pull request is still open**: the value is added to it, so you merge one pull request. If someone pushed to it since the preview, prepare it again - **AppFig isn't in the app yet**: the install pull request comes first, with this value ticked ## 6. Results - A **plain change** shows how many users received each value since you published it. It's a count, not a comparison: to know whether a change helped, test it. - A **test** shows each group against control, with the likely range, and calls a winner only when the difference is unlikely to be chance. Give the winner to everyone in one click; it's saved as a draft for you to publish. ## AI Agent Describe a change in plain words ("fewer reminders for readers who haven't finished a chapter"). The agent knows your events and the values your code reads, writes the rule and saves it as a draft. It only prepares drafts, and it stays on your app's values, rules and tests. ## AI allowance Every AI feature spends from one monthly allowance per company, shown on the AI Agent screen. It renews on the 1st; a request that fails is given back. | What AI does | Credits (about) | |---|---| | A message to the AI Agent | a few | | A new list of suggested actions | a few | | A recommendation | about 10 | | Reading the code and opening an install pull request | about 50 | What a request uses depends on its size: 1,000 credits cover about 20 install pull requests or hundreds of questions. | Plan | AI | |---|---| | Lite (free) | One AI setup: ideas from your reviews, a code scan and an install pull request | | Full ($99 per app a month) | 1,000 credits a month per app (500 from the 11th app), shared across your apps | When credits run out, AI pauses until the 1st. Your configs and experiments keep running. Answers AppFig already has stored cost nothing. ## What AppFig never does - Write to your code on its own: changes reach your repository only as a pull request you open and merge - Change your other tools: GitHub before the pull request, Google Analytics and Firebase are read-only - Reach users without you: changes, tests and AI suggestions are drafts until you publish - Break your build: a change that would leave a file parsing worse is dropped If AppFig can't be reached, your app uses the values from its own code, as it did before the install. ## Next Steps - **[Experiments](https://appfig.com/docs/experiments)** - Test several values at once, and how results are measured - **[Concepts](https://appfig.com/docs/concepts)** - Features, rules and environments - **[Flutter Integration](https://appfig.com/docs/flutter-integration)** - Installing the SDK by hand --- # How It Works Source: https://appfig.com/docs/how-it-works A detailed look at how AppFig evaluates rules on the client side. ## The Big Picture ``` ┌─────────────────────────────────────────────────────────────┐ │ 1. INITIALIZATION │ │ Your app starts → SDK loads rules (from file or server) │ └─────────────────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────────────────┐ │ 2. TRACKING │ │ Your app logs events, sets properties │ │ - AppFig.LogEvent("level_complete") │ │ - AppFig.SetUserProperty("tier", "premium") │ │ All stored locally in memory │ └─────────────────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────────────────┐ │ 3. EVALUATION (when you call GetFeatureValue) │ │ SDK checks rules against stored events/properties │ │ - Loops through rules in order │ │ - First matching rule wins │ │ - Returns value or null │ └─────────────────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────────────────┐ │ 4. YOUR APP USES THE VALUE │ │ if (value == "on") { EnableFeature(); } │ └─────────────────────────────────────────────────────────────┘ ``` ## Step-by-Step: Rule Evaluation Let's walk through exactly what happens when you call `GetFeatureValue()`. ### Setup You have this feature defined: ```json Feature: "veteran_bonus" Rules: [ { "conditions": { "events": { "mode": "simple", "operator": "AND", "items": [ { "key": "level_complete", "count": { "operator": ">=", "value": 10 } } ] }, "user_properties": [], "device": [] }, "value": "2x" } ] ``` Your app has done this: ```csharp AppFig.LogEvent("level_complete"); // Called 12 times AppFig.GetFeatureValue("veteran_bonus"); // ← What happens now? ``` ### Evaluation Process **Step 1: Find the feature's rules** ``` SDK looks up "veteran_bonus" in its rules dictionary Found: 1 rule to evaluate ``` **Step 2: Loop through rules (first match wins)** ``` Evaluating Rule #1... ``` **Step 3: Check event conditions** ``` Event condition: "level_complete" count >= 10 SDK counts matching events in history: - Found 12 "level_complete" events - Compare: 12 >= 10? ✓ YES Event conditions: PASS ✓ ``` **Step 4: Check user property conditions** ``` User property conditions: [] (empty) No conditions to check User property conditions: PASS ✓ ``` **Step 5: Check device conditions** ``` Device conditions: [] (empty) No conditions to check Device conditions: PASS ✓ ``` **Step 6: All conditions passed!** ``` ✓ Events: PASS ✓ User Properties: PASS ✓ Device: PASS Rule #1 MATCHES! Return value: "2x" ``` **Result:** ```csharp string bonus = AppFig.GetFeatureValue("veteran_bonus"); // bonus = "2x" ``` ## Event History The SDK maintains an in-memory list of all events you log: ```csharp AppFig.LogEvent("level_complete"); // Event #1 AppFig.LogEvent("purchase_made"); // Event #2 AppFig.LogEvent("level_complete"); // Event #3 ``` **Stored as:** ``` Event History = [ { name: "level_complete", timestamp: 2025-01-15T10:00:00Z, params: {} }, { name: "purchase_made", timestamp: 2025-01-15T10:05:00Z, params: {} }, { name: "level_complete", timestamp: 2025-01-15T10:10:00Z, params: {} } ] ``` When a rule checks `"level_complete" count >= 2`, the SDK: 1. Filters history for events named "level_complete" 2. Counts them (2 events found) 3. Compares: 2 >= 2? Yes ✓ ## Event Modes ### Simple Mode (AND/OR) Checks if events exist with certain criteria. **Example: User completed 10+ levels AND made a purchase** ```json { "events": { "mode": "simple", "operator": "AND", "items": [ { "key": "level_complete", "count": { "operator": ">=", "value": 10 } }, { "key": "purchase_made", "count": { "operator": ">=", "value": 1 } } ] } } ``` **Evaluation:** ``` Check: level_complete count >= 10? (found 12) ✓ Check: purchase_made count >= 1? (found 1) ✓ Both pass → Rule matches! ``` ### Sequence Mode (Direct/Indirect) Checks if events occurred in a specific order. **Example: User completed tutorial → made purchase → completed level** ```json { "events": { "mode": "sequence", "ordering": "direct", "steps": [ { "key": "tutorial_complete" }, { "key": "purchase_made" }, { "key": "level_complete" } ] } } ``` **Direct ordering:** Events must occur **consecutively** (no other events between them) ``` Event history: 1. tutorial_complete ← Step 1 ✓ 2. purchase_made ← Step 2 ✓ 3. level_complete ← Step 3 ✓ Sequence matches! ``` **Indirect ordering:** Events must occur **in order** but can have other events between ``` Event history: 1. tutorial_complete ← Step 1 ✓ 2. app_open (ignored) 3. settings_changed (ignored) 4. purchase_made ← Step 2 ✓ 5. level_complete ← Step 3 ✓ Sequence matches! ``` ## Property Matching ### User Properties Set by your app, checked against rules: ```csharp AppFig.SetUserProperty("subscription_tier", "premium"); ``` **Rule checks:** ```json { "user_properties": [ { "key": "subscription_tier", "value": { "operator": "==", "value": "premium" } } ] } ``` **Evaluation:** ``` Lookup: user_properties["subscription_tier"] → "premium" Compare: "premium" == "premium" → ✓ PASS ``` ### Device Properties Auto-detected by SDK, no setup needed: ``` Device properties (auto-populated): { "platform": "iOS", "os_version": "17.0", "language": "en-US", "country": "US", "device_brand": "Apple", "device_model": "iPhone 15" } ``` **Rule checks:** ```json { "device": [ { "key": "platform", "value": { "operator": "in", "value": ["iOS", "Android"] } } ] } ``` **Evaluation:** ``` Lookup: device["platform"] → "iOS" Compare: "iOS" in ["iOS", "Android"] → ✓ PASS ``` ## Time Windows Events can be filtered by time: ```json { "key": "level_complete", "count": { "operator": ">=", "value": 5 }, "within_last_days": 7 } ``` **Evaluation:** ``` 1. Filter events: name == "level_complete" Found: 12 events 2. Filter by time: timestamp >= (now - 7 days) Found: 3 events (9 were older than 7 days) 3. Check count: 3 >= 5? ✗ FAIL Rule does not match ``` ## Operators ### Comparison Operators | Operator | Description | Example | |----------|-------------|---------| | `==` | Equals | "premium" == "premium" | | `!=` | Not equals | "free" != "premium" | | `>` | Greater than | 10 > 5 | | `<` | Less than | 3 < 10 | | `>=` | Greater or equal | 10 >= 10 | | `<=` | Less or equal | 5 <= 10 | ### Array Operators | Operator | Description | Example | |----------|-------------|---------| | `in` | Value in array | "iOS" in ["iOS", "Android"] | | `not_in` | Value not in array | "Windows" not_in ["iOS", "Android"] | ### String Operators | Operator | Description | Example | |----------|-------------|---------| | `contains` | String contains substring | "hello world" contains "world" | ## Negation (NOT) Any condition can be negated with `"not": true`: ```json { "key": "purchase_made", "count": { "operator": ">=", "value": 1 }, "not": true } ``` **Evaluation:** ``` 1. Check condition: purchase_made count >= 1? (found 0) → FAIL 2. Apply NOT: !FAIL → ✓ PASS Matches users who have NOT made a purchase ``` ## Performance: Why It's Fast AppFig is optimized for high-performance client-side evaluation: - **In-Memory Processing** - Rules, events, and properties are kept in memory for fast access - **Smart Caching** - Feature values are cached after evaluation and invalidated only when relevant data changes - **Efficient Evaluation** - The rule engine is optimized to minimize computational overhead These optimizations ensure feature checks are extremely fast, with subsequent checks being nearly instantaneous due to caching. ## Rule Evaluation Order Rules are evaluated in the order you define them. **First match wins.** ```json Feature: "discount" Rules: [ Rule 1: IF premium user → "50% off" Rule 2: IF any user → "10% off" ] ``` **Premium user evaluation:** ``` Check Rule 1: premium user? ✓ YES → Return "50% off" (Rule 2 never evaluated) ``` **Free user evaluation:** ``` Check Rule 1: premium user? ✗ NO Check Rule 2: any user? ✓ YES → Return "10% off" ``` ## What Gets Sent to the Server? **Short answer: Almost nothing.** When you initialize, and once per poll interval: ``` SDK → CDN: "Has the rule set changed?" (a small file) CDN → SDK: The rules JSON, only when it changed (then cached on the device) ``` When you call `GetFeatureValue()`: ``` No network call! Everything evaluated locally. ``` Schema discovery (paid plans), so the rule builder can offer your event and property names: ``` SDK → Server: event names, parameter names and example values it has not reported before ``` - Sent by about 1% of devices, and by at most 100 devices per app version. The other devices are told they are not needed and stop asking until the app version changes. - At most once every 12 hours per device. - Up to 20 example values per parameter or property. A value that looks like an email is sent as `[email]`, and long values are cut to 50 characters. - No event history, and the device is identified only by an anonymous hash. ## Next Steps - **[Rule Schema Reference](https://appfig.com/docs/rule-schema)** - All rule options and operators - **[Testing Guide](https://appfig.com/docs/testing)** - Test your rules --- # Android SDK Integration Guide Source: https://appfig.com/docs/android-integration Complete guide to integrating AppFig into your Android application. ## Installation > **SDK Download Repository:** [https://github.com/smartconfigui/AppFig-SDKs](https://github.com/smartconfigui/AppFig-SDKs) **Requirements:** Android API 21+ (Android 5.0 Lollipop), Android Studio 4.0+, Gradle 7.0+ ### Step 1 — Add the dependency In your app module's build file. **Groovy (build.gradle):** ```gradle dependencies { implementation 'com.appfig:appfig-android:2.5.0' } ``` **Kotlin DSL (build.gradle.kts):** ```kotlin dependencies { implementation("com.appfig:appfig-android:2.5.0") } ``` The SDK is on Maven Central, which a standard Android project already has in its repositories (`mavenCentral()`). The libraries it needs (OkHttp, Gson, the Kotlin standard library) are pulled in automatically, and it declares the internet permission itself. ### Step 2 — Sync Gradle Android Studio → "Sync Project with Gradle Files". ### Without Maven Central Projects that cannot use Maven Central can copy `android/AppFigAndroidSDK.aar` from the [SDK repository](https://github.com/smartconfigui/AppFig-SDKs/tree/v2.5.0/android) into `app/libs/` and add `implementation files('libs/AppFigAndroidSDK.aar')` together with `com.squareup.okhttp3:okhttp:4.12.0` and `com.google.code.gson:gson:2.10.1`. ## Quick Start ### Initialize ```kotlin import com.appfig.sdk.AppFig class MyApplication : Application() { override fun onCreate() { super.onCreate() // Initialize AppFig with auto-refresh AppFig.init( context = this, companyId = "your-company-id", tenantId = "your-tenant-id", env = "prod", apiKey = "your-api-key", autoRefresh = true, pollInterval = 3600000 // 1 hour ) // Log events AppFig.logEvent("app_open") // Check features if (AppFig.isFeatureEnabled("double_xp")) { applyDoubleXP() } val maxLives = AppFig.getFeatureValue("max_lives")?.toIntOrNull() ?: 3 } } ``` ## When to Do What: Timing Guide Understanding WHEN to call each SDK method is crucial for proper Android integration: | Action | When to Call | Where to Place | Code Example | |--------|-------------|----------------|--------------| | **Initialize SDK** | Once at app startup | `Application.onCreate()` | `AppFig.init(...)` | | **Log Events** | Immediately after user action | onClick listeners, lifecycle methods | `AppFig.logEvent("button_click")` | | **Set User Properties** | Once at login, when value changes | Auth callback, state change | `AppFig.setUserProperty("tier", "premium")` | | **Evaluate Features** | Right before you need the value | onCreate, onResume, before decisions | `AppFig.getFeatureValue("max_lives")` | | **Apply Features** | Immediately after evaluation | Same method as evaluation | `if (enabled) showUI()` | | **Refresh Rules** | On demand (auto-refresh handles this) | Manual: Settings screen | `AppFig.refreshRules()` | ### Complete Lifecycle Example ```kotlin import android.app.Application import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.appfig.sdk.AppFig class MyApplication : Application() { override fun onCreate() { super.onCreate() // 1. INITIALIZE: Once at app startup AppFig.init( context = this, companyId = "your-company-id", tenantId = "your-tenant-id", env = "prod", apiKey = "your-api-key" ) // 2. TRACK: Log app open AppFig.logEvent("app_open") } } class MainActivity : AppCompatActivity() { private var playerLives = 3 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // 3. EVALUATE: Check features when activity created checkWelcomeBonus() configureGameSettings() } private fun checkWelcomeBonus() { // Evaluate right before using if (AppFig.isFeatureEnabled("welcome_bonus")) { // 4. APPLY: Show bonus immediately findViewById(R.id.welcomePanel).visibility = View.VISIBLE grantBonus(500) } else { findViewById(R.id.welcomePanel).visibility = View.GONE } } private fun configureGameSettings() { // Evaluate with fallback val maxLives = AppFig.getFeatureValue("max_lives")?.toIntOrNull() ?: 3 playerLives = maxLives // Apply to UI findViewById(R.id.livesText).text = "Lives: $playerLives" } fun onLevelComplete(view: View) { // TRACK: Log immediately after action AppFig.logEvent("level_complete", mapOf( "level" to currentLevel.toString() )) // Re-evaluate features that depend on level checkNewUnlocks() } fun onSubscriptionPurchased(tier: String) { // Update property when it changes AppFig.setUserProperty("subscription_tier", tier) // Re-evaluate premium features updatePremiumFeatures() } } ``` ### Timing Best Practices #### Initialize Once in Application Class ```kotlin // ✅ CORRECT: Initialize in Application.onCreate() class MyApplication : Application() { override fun onCreate() { super.onCreate() AppFig.init(context = this, companyId = "...", tenantId = "...", env = "prod", apiKey = "...") } } // ❌ WRONG: Don't initialize in every activity class MyActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AppFig.init(...) // Bad! SDK already initialized } } ``` #### Log Events Immediately ```kotlin // ✅ CORRECT: Log right when action happens fun onPurchaseClicked(view: View) { AppFig.logEvent("purchase_initiated") showPurchaseDialog() } // ❌ WRONG: Don't batch events private val pendingEvents = mutableListOf() fun onLevelComplete() { pendingEvents.add("level_complete") // Bad! } ``` #### Cache Feature Values ```kotlin // ✅ CORRECT: Check once and cache class GameActivity : AppCompatActivity() { private var hasDoubleXP = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) hasDoubleXP = AppFig.isFeatureEnabled("double_xp") } fun calculateXP(baseXP: Int): Int { return if (hasDoubleXP) baseXP * 2 else baseXP } } // ❌ WRONG: Don't check repeatedly fun update() { if (AppFig.isFeatureEnabled("double_xp")) { // Bad! applyDoubleXP() } } ``` --- ## API Reference ### Initialization ```kotlin AppFig.init( context: Context, // Required: Application context companyId: String, // Required: Your company ID tenantId: String, // Required: Your tenant/project ID env: String, // Required: "dev" or "prod" apiKey: String, // Required: Your API key autoRefresh: Boolean = true, // Optional: Enable auto-refresh (default: true) ✨ NEW DEFAULT pollInterval: Long = 43200000L, // Optional: leave out to follow your plan debugMode: Boolean = false, // Optional: Enable debug logging (default: false) ✨ NEW sessionTimeoutMs: Long = 1800000L, // Optional: 30 minutes (default: 30 min) ✨ NEW maxEvents: Int = 5000, // Optional: Max events (default: 5000, max: 100000) maxEventAgeDays: Int = 7, // Optional: Max age in days (default: 7, max: 365) cdnBaseUrl: String? = null // Optional: rules host (default: production) 🆕 2.3 ) ``` **Parameters:** - `context` (required) - Application context (use `this` from Application.onCreate() or activity) - `companyId` (required) - Your company ID from AppFig dashboard - `tenantId` (required) - Your tenant/project ID from AppFig dashboard - `env` (required) - Environment: `"dev"` or `"prod"` - `apiKey` (required) - Your API key from AppFig dashboard - `autoRefresh` (optional) - Enable automatic background rule updates (default: **true**) ⚠️ **Breaking Change** Refreshing pauses while no screen of your app is visible and resumes when the app comes back to the foreground 🆕 **New in 2.4**. - `pollInterval` (optional) - Auto-refresh interval in milliseconds. Leave it out and the SDK checks for changes every minute, on every plan 🆕 **New in 2.3**. A value you set is kept, but never faster than your plan allows. - `debugMode` (optional) - Enable debug logging to Logcat (default: false) 🆕 **New in v2.0** - `sessionTimeoutMs` (optional) - Session timeout in milliseconds (default: 1800000L = 30 min, range: 60000-7200000) 🆕 **New in v2.0** - `maxEvents` (optional) - Maximum events to store in SharedPreferences (100-100000, default: 5000) - `maxEventAgeDays` (optional) - Maximum age of events in days (1-365, default: 7) - `cdnBaseUrl` (optional) - The rules host to read from, e.g. `https://rules-stage.appfig.com` for a staging build. Leave it out for production (`https://rules-prod.appfig.com`). Must start with `https://`. 🆕 **New in 2.3** **Examples:** ```kotlin // Basic initialization (auto-refresh enabled by default) AppFig.init(this, "acme-games", "space-shooter", "prod", "sk_live_abc123") // With a fixed poll interval (1 hour) AppFig.init( context = this, companyId = "acme-games", tenantId = "space-shooter", env = "prod", apiKey = "sk_live_abc123", autoRefresh = true, // Explicit (but this is already the default) pollInterval = 3600000L // 1 hour ) // With debug mode enabled (useful during development) AppFig.init( context = this, companyId = "acme-games", tenantId = "space-shooter", env = "dev", // Use dev environment apiKey = "sk_test_abc123", autoRefresh = true, pollInterval = 600000L, // 10 minutes for faster testing debugMode = true // See all SDK operations in Logcat ) // With all parameters customized AppFig.init( context = this, companyId = "acme-games", tenantId = "space-shooter", env = "prod", apiKey = "sk_live_abc123", autoRefresh = true, pollInterval = 3600000L, debugMode = false, sessionTimeoutMs = 900000L, // 15 minutes instead of 30 maxEvents = 10000, // Store more events maxEventAgeDays = 30 // Keep events for 30 days ) // Disable auto-refresh (opt-out, manual refresh only) AppFig.init( context = this, companyId = "acme-games", tenantId = "space-shooter", env = "prod", apiKey = "sk_live_abc123", autoRefresh = false // Must call refreshRules() manually ) ``` ### Logging Events ```kotlin AppFig.logEvent(eventName: String, parameters: Map? = null) ``` **Examples:** ```kotlin // Simple event AppFig.logEvent("level_complete") // Event with parameters AppFig.logEvent("purchase_made", mapOf( "item_id" to "sword_legendary", "price" to "9.99", "currency" to "USD" )) // Screen view (auto-tracked by SDK too) AppFig.logScreenView("main_menu", "settings") ``` ### Checking Features ```kotlin AppFig.isFeatureEnabled(feature: String): Boolean AppFig.getFeatureValue(feature: String): String? ``` **Examples:** ```kotlin // Boolean check (returns true if value == "on") if (AppFig.isFeatureEnabled("new_ui")) { loadNewUI() } else { loadOldUI() } // Get actual value val maxLives = AppFig.getFeatureValue("max_lives") if (maxLives != null) { playerLives = maxLives.toIntOrNull() ?: 3 } // Handle null (no matching rules) val bonus = AppFig.getFeatureValue("veteran_bonus") if (bonus == null) { Log.d("AppFig", "No bonus active") } else { applyBonus(bonus) // "2x", "1.5x", etc. } ``` ### Setting Properties ```kotlin // User properties AppFig.setUserProperty(key: String, value: String) AppFig.removeUserProperty(key: String) // Device properties AppFig.setDeviceProperty(key: String, value: String) AppFig.removeDeviceProperty(key: String) // App version AppFig.setAppVersion(version: String) ``` **Examples:** ```kotlin // User properties AppFig.setUserProperty("subscription_tier", "premium") AppFig.setUserProperty("account_age_days", "30") AppFig.setUserProperty("player_level", "15") // Device properties (most are auto-detected) AppFig.setAppVersion("1.2.3") AppFig.setDeviceProperty("graphics_quality", "high") // Remove properties AppFig.removeUserProperty("subscription_tier") ``` ### Auto-Detected Device Properties These are automatically set by the SDK on initialization: ``` platform "Android" os_version "13", "12", "11" language "English", "Japanese", "Spanish" timezone "America/Los_Angeles", "Asia/Tokyo" country "US", "JP", "GB" (requires internet on first run) device_brand "Samsung", "Google", "Huawei", "OnePlus" device_model "SM-G998B", "Pixel 8", "OnePlus 11" ``` ### Session Tracking Automatically tracked: ```kotlin // These events are logged automatically: "first_open" // First time app opens (persisted in SharedPreferences) "session_start" // App comes to foreground "session_end" // App goes to background or 10 minutes of inactivity "screen_view" // When you call logScreenView() ``` ### Manual Refresh ```kotlin AppFig.refreshRules() // Manually reload rules from CDN ``` **Example:** ```kotlin // Manually refresh rules (useful for pull-to-refresh) AppFig.refreshRules() ``` **Note:** `setAutoRefresh()` and `setPollInterval()` are deprecated. Use the `autoRefresh` and `pollInterval` parameters in `init()` instead. ### Feature Reset (Recurring Triggers) ```kotlin AppFig.resetFeature(featureName: String) AppFig.resetAllFeatures() ``` Reset a feature's cached value and force re-evaluation. Useful for implementing recurring triggers like "show popup every 3 events". **Example:** ```kotlin // Check if feature is enabled if (AppFig.isFeatureEnabled("level_complete_popup")) { showPopup("You've completed 3 levels!") // Reset so it triggers again after next 3 events AppFig.resetFeature("level_complete_popup") } // With event logging fun onLevelComplete(level: Int) { AppFig.logEvent("level_complete", mapOf("level" to level.toString())) // Check for milestone reward if (AppFig.isFeatureEnabled("milestone_reward")) { showReward() AppFig.resetFeature("milestone_reward") } } ``` **Use Cases:** - Show popup every N events (e.g., every 3 level completions) - Recurring promotions after X purchases - Periodic reward unlocks - Time-based feature re-triggers See [Feature Reset Guide](../../SDKs/FEATURE_RESET_GUIDE.md) for detailed examples. ### Debugging ```kotlin AppFig.hasRulesLoaded(): Boolean AppFig.getEventHistoryStats(): Map ``` **Example:** ```kotlin if (AppFig.hasRulesLoaded()) { Log.d("AppFig", "Rules are loaded") } val stats = AppFig.getEventHistoryStats() Log.d("AppFig", "Event count: ${stats["count"]}") Log.d("AppFig", "Size: ${stats["sizeMB"]} MB") ``` ## Best Practices ### 1. Initialize in Application Class ```kotlin class MyApplication : Application() { override fun onCreate() { super.onCreate() AppFig.init( context = this, companyId = "company", tenantId = "tenant", env = "prod", apiKey = "api-key", autoRefresh = true ) } } ``` Don't forget to register in `AndroidManifest.xml`: ```xml ``` ### 2. Cache Feature Values ```kotlin // ❌ Bad: Checks every frame override fun onDraw(canvas: Canvas) { if (AppFig.isFeatureEnabled("double_xp")) { // ... } } // ✅ Good: Check once, store result private val hasDoubleXP by lazy { AppFig.isFeatureEnabled("double_xp") } override fun onDraw(canvas: Canvas) { if (hasDoubleXP) { // ... } } ``` ### 3. Handle Null Values ```kotlin val maxLives = AppFig.getFeatureValue("max_lives")?.toIntOrNull() ?: 5 // fallback ``` ### 4. Log Events Liberally ```kotlin fun completeLevel(level: Int, stars: Int, timeSeconds: Int) { AppFig.logEvent("level_complete", mapOf( "level_number" to level.toString(), "time_seconds" to timeSeconds.toString(), "stars" to stars.toString() )) } ``` ## Troubleshooting ### AAR not recognized by Android Studio **Problem:** Android Studio doesn't find AppFig classes **Solutions:** 1. Verify `AppFigAndroidSDK.aar` is in `app/libs/` folder 2. Check `build.gradle` has `implementation files('libs/AppFigAndroidSDK.aar')` 3. Sync Gradle files (File → Sync Project with Gradle Files) 4. Clean and rebuild project (Build → Clean Project, then Build → Rebuild Project) ### "AppFig not initialized" **Problem:** Calling SDK methods before `init()` **Solution:** ```kotlin class MyApplication : Application() { override fun onCreate() { super.onCreate() AppFig.init(...) // Must be first! AppFig.logEvent("app_open") // Now OK } } ``` ### Feature always returns null **Problem:** No rules match for this feature **Solutions:** 1. Check feature name spelling (case-sensitive) 2. Verify rules are loaded: `AppFig.hasRulesLoaded()` 3. Log relevant events/properties before checking feature 4. Check Logcat for AppFig debug messages ### Rules not updating **Problem:** Changes in dashboard not reflected in app **Solutions:** 1. Wait for the refresh interval (one minute) 2. Call `AppFig.refreshRules()` manually 3. Check Logcat for "AppFig" tag messages 4. Verify internet connection ## Performance Tips ### Event History Management The SDK automatically manages event history to maintain optimal performance. Events are automatically trimmed based on: - Maximum event count (default: 5000) - Maximum event age (default: 7 days) ### Memory and CPU Usage AppFig has minimal memory and CPU overhead: - Low memory footprint suitable for mobile devices - Fast feature checks with intelligent caching - Efficient rule evaluation ## Next Steps - **[Rule Schema](https://appfig.com/docs/rule-schema)** - All rule options - **[Testing Guide](https://appfig.com/docs/testing)** - Test your features --- # Flutter Integration Source: https://appfig.com/docs/flutter-integration AppFig for Flutter: feature flags, remote config and A/B tests evaluated on the device. This package is a thin layer over the native AppFig SDKs for Android and iOS, so rules behave exactly as they do in a native app. ## Install In `pubspec.yaml`: ```yaml dependencies: appfig_flutter: git: url: https://github.com/smartconfigui/AppFig-SDKs.git path: flutter ref: v2.5.0 ``` Nothing else is needed: the Android SDK is pulled from JitPack by the plugin and the iOS framework ships inside it. Minimum versions: Android 5.0 (API 21), iOS 12. ## Use ```dart import 'package:appfig_flutter/appfig_flutter.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await AppFig.init(companyId: 'your-company', tenantId: 'your-app', env: 'prod', apiKey: 'your-api-key'); runApp(const MyApp()); } // Read a value (null when no rule matches) final maxSongs = int.tryParse(await AppFig.getFeatureValue('max_songs') ?? '') ?? 25; // Tell AppFig what the user does and who they are; rules can target on both AppFig.logEvent('add_song', parameters: {'source': 'import'}); AppFig.setUserProperty('subscription_tier', 'free'); // Re-read values when new rules arrive AppFig.onRulesUpdated.listen((_) => refreshLimits()); ``` `init` completes when rules are available or after `readyTimeout` (5 seconds by default), so values read right after it are real. ## A/B tests and analytics A/B tests work without a user id: a device without one is assigned by its device id, and an assignment stays with the device across restarts and sign-in. Call `setUserId` before `init` if a signed-in user should get the same variant on every device. To see experiments in your analytics tool, connect it once at startup: ```dart AppFig.connectAnalytics( setUserProperty: (name, value) => FirebaseAnalytics.instance.setUserProperty(name: name, value: value.isEmpty ? null : value), logEvent: (name, parameters) => FirebaseAnalytics.instance.logEvent(name: name, parameters: parameters), ); ``` `setUserProperty` receives one property per running experiment (`af_` = variant). `logEvent` receives two events, each once per device: | Event | Parameters | When | |---|---|---| | `appfig_experiment` | `experiment`, `variant` | The device enters an experiment. | | `appfig_feature` | `feature`, `feature_value` | The app reads a feature. Sent again only when the value this device gets changes. | A feature the app never reads sends nothing. The two callbacks can call any analytics tool. ## API `init`, `getFeatureValue`, `isFeatureEnabled`, `hasRulesLoaded`, `logEvent`, `logScreenView`, `setUserProperty`, `removeUserProperty`, `setDeviceProperty`, `removeDeviceProperty`, `setAppVersion`, `setUserId`, `getUserId`, `refreshRules`, `resetSession`, `connectAnalytics`, and the streams `onRulesUpdated` and `onVariantAssigned`. ## Next Steps - **[Guided Setup](https://appfig.com/docs/guided-setup)** - Let AppFig find the values in your Flutter code and open the install pull request - **[A/B Testing Reference](https://appfig.com/docs/ab-testing)** - How assignment and analytics work --- # iOS SDK Integration Guide Source: https://appfig.com/docs/ios-integration Complete guide to integrating AppFig into your iOS application. ## Installation > **SDK Download Repository:** [https://github.com/smartconfigui/AppFig-SDKs](https://github.com/smartconfigui/AppFig-SDKs) **Requirements:** iOS 12.0+, Xcode 13+, Swift 5.0+ ### Swift Package Manager (recommended) 1. In Xcode: **File > Add Package Dependencies** 2. Enter the URL: ``` https://github.com/smartconfigui/AppFig-SDKs ``` 3. Choose version `2.5.0` or later and add the **AppFigSDK** library to your app target. ### CocoaPods Add to your `Podfile`, then run `pod install`: ```ruby pod 'AppFigSDK', :git => 'https://github.com/smartconfigui/AppFig-SDKs.git', :tag => 'v2.5.0' ``` ### By hand Download `ios/AppFigSDK.xcframework` from the [SDK repository](https://github.com/smartconfigui/AppFig-SDKs/tree/v2.5.0/ios), drag it into your Xcode project ("Copy items if needed"), and under your app target's **General > Frameworks, Libraries, and Embedded Content** set it to **Embed & Sign**. ### Import in your code ```swift import AppFigSDK ``` **Note:** No external dependencies required. The XCFramework is self-contained. ## Quick Start ### Initialize ```swift import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Initialize AppFig with auto-refresh AppFig.initialize( companyId: "your-company-id", tenantId: "your-tenant-id", env: "prod", apiKey: "your-api-key", autoRefresh: true, pollInterval: 3600000 // 1 hour ) // Log events AppFig.logEvent(name: "app_open") // Check features if AppFig.isFeatureEnabled("double_xp") { applyDoubleXP() } if let maxLives = AppFig.getFeatureValue("max_lives") { playerLives = Int(maxLives) ?? 3 } return true } } ``` ## When to Do What: Timing Guide Understanding WHEN to call each SDK method is crucial for proper iOS integration: | Action | When to Call | Where to Place | Code Example | |--------|-------------|----------------|--------------| | **Initialize SDK** | Once at app launch | `didFinishLaunchingWithOptions` | `AppFig.initialize(...)` | | **Log Events** | Immediately after user action | IBAction methods, delegates | `AppFig.logEvent(name: "button_tap")` | | **Set User Properties** | Once at login, when value changes | Auth callback, state change | `AppFig.setUserProperty(key: "tier", value: "premium")` | | **Evaluate Features** | Right before you need the value | viewDidLoad, viewWillAppear | `AppFig.getFeatureValue("max_lives")` | | **Apply Features** | Immediately after evaluation | Same method as evaluation | `if enabled { showUI() }` | | **Refresh Rules** | On demand (auto-refresh handles this) | Manual: Settings screen | `AppFig.refreshRules()` | ### Complete Lifecycle Example ```swift import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 1. INITIALIZE: Once at app launch AppFig.initialize( companyId: "your-company-id", tenantId: "your-tenant-id", env: "prod", apiKey: "your-api-key" ) // 2. TRACK: Log app open event AppFig.logEvent(name: "app_open") return true } } class MainViewController: UIViewController { @IBOutlet weak var welcomePanel: UIView! @IBOutlet weak var livesLabel: UILabel! private var playerLives = 3 override func viewDidLoad() { super.viewDidLoad() // 3. EVALUATE: Check features when view loads checkWelcomeBonus() configureGameSettings() } func checkWelcomeBonus() { // Evaluate right before using if AppFig.isFeatureEnabled("welcome_bonus") { // 4. APPLY: Show bonus immediately welcomePanel.isHidden = false grantBonus(coins: 500) } else { welcomePanel.isHidden = true } } func configureGameSettings() { // Evaluate with fallback if let maxLivesStr = AppFig.getFeatureValue("max_lives"), let maxLives = Int(maxLivesStr) { playerLives = maxLives } else { playerLives = 3 // Fallback } // Apply to UI livesLabel.text = "Lives: \(playerLives)" } @IBAction func onLevelComplete(_ sender: UIButton) { // TRACK: Log immediately after action AppFig.logEvent(name: "level_complete", parameters: [ "level": "\(currentLevel)" ]) // Re-evaluate features that depend on level checkNewUnlocks() } func onSubscriptionPurchased(tier: String) { // Update property when it changes AppFig.setUserProperty(key: "subscription_tier", value: tier) // Re-evaluate premium features updatePremiumFeatures() } } ``` ### Timing Best Practices #### Initialize Once at Launch ```swift // ✅ CORRECT: Initialize in app delegate func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { AppFig.initialize(companyId: "...", tenantId: "...", env: "prod", apiKey: "...") return true } // ❌ WRONG: Don't initialize in every view controller class MyViewController: UIViewController { override func viewDidLoad() { AppFig.initialize(...) // Bad! SDK already initialized } } ``` #### Log Events Immediately ```swift // ✅ CORRECT: Log right when action happens @IBAction func purchaseButtonTapped(_ sender: UIButton) { AppFig.logEvent(name: "purchase_initiated") showPurchaseDialog() } // ❌ WRONG: Don't batch events var pendingEvents: [String] = [] func onLevelComplete() { pendingEvents.append("level_complete") // Bad! } ``` #### Cache Feature Values ```swift // ✅ CORRECT: Check once and cache class GameViewController: UIViewController { private var hasDoubleXP = false override func viewDidLoad() { super.viewDidLoad() hasDoubleXP = AppFig.isFeatureEnabled("double_xp") } func calculateXP(_ baseXP: Int) -> Int { return hasDoubleXP ? baseXP * 2 : baseXP } } // ❌ WRONG: Don't check repeatedly func update() { if AppFig.isFeatureEnabled("double_xp") { // Bad! applyDoubleXP() } } ``` --- ## API Reference ### Initialization ```swift AppFig.initialize( companyId: String, // Required: Your company ID tenantId: String, // Required: Your tenant/project ID env: String, // Required: "dev" or "prod" apiKey: String, // Required: Your API key autoRefresh: Bool = true, // Optional: Enable auto-refresh (default: true) ✨ NEW DEFAULT pollInterval: TimeInterval = 43200000, // Optional: leave out to follow your plan debugMode: Bool = false, // Optional: Enable debug logging (default: false) ✨ NEW sessionTimeoutMs: Int64 = 1800000, // Optional: 30 minutes (default: 30 min) ✨ NEW maxEvents: Int = 5000, // Optional: Max events (default: 5000, max: 100000) maxEventAgeDays: Int = 7, // Optional: Max age in days (default: 7, max: 365) cdnBaseUrl: String? = nil // Optional: rules host (default: production) 🆕 2.3 ) ``` **Parameters:** - `companyId` (required) - Your company ID from AppFig dashboard - `tenantId` (required) - Your tenant/project ID from AppFig dashboard - `env` (required) - Environment: `"dev"` or `"prod"` - `apiKey` (required) - Your API key from AppFig dashboard - `autoRefresh` (optional) - Enable automatic background rule updates (default: **true**) ⚠️ **Breaking Change** - `pollInterval` (optional) - Auto-refresh interval in milliseconds. Leave it out and the SDK checks for changes every minute, on every plan 🆕 **New in 2.3**. A value you set is kept, but never faster than your plan allows. - `debugMode` (optional) - Enable debug logging to console (default: false) 🆕 **New in v2.0** - `sessionTimeoutMs` (optional) - Session timeout in milliseconds (default: 1800000 = 30 min, range: 60000-7200000) 🆕 **New in v2.0** - `maxEvents` (optional) - Maximum events to store in UserDefaults (100-100000, default: 5000) - `maxEventAgeDays` (optional) - Maximum age of events in days (1-365, default: 7) - `cdnBaseUrl` (optional) - The rules host to read from, e.g. `https://rules-stage.appfig.com` for a staging build. Leave it out for production (`https://rules-prod.appfig.com`). Must start with `https://`. 🆕 **New in 2.3** **Examples:** ```swift // Basic initialization (auto-refresh enabled by default) AppFig.initialize( companyId: "acme-games", tenantId: "space-shooter", env: "prod", apiKey: "sk_live_abc123" ) // With a fixed poll interval (1 hour) AppFig.initialize( companyId: "acme-games", tenantId: "space-shooter", env: "prod", apiKey: "sk_live_abc123", autoRefresh: true, // Explicit (but this is already the default) pollInterval: 3600000 // 1 hour ) // With debug mode enabled (useful during development) AppFig.initialize( companyId: "acme-games", tenantId: "space-shooter", env: "dev", // Use dev environment apiKey: "sk_test_abc123", autoRefresh: true, pollInterval: 600000, // 10 minutes for faster testing debugMode: true // See all SDK operations in console ) // With all parameters customized AppFig.initialize( companyId: "acme-games", tenantId: "space-shooter", env: "prod", apiKey: "sk_live_abc123", autoRefresh: true, pollInterval: 3600000, debugMode: false, sessionTimeoutMs: 900000, // 15 minutes instead of 30 maxEvents: 10000, // Store more events maxEventAgeDays: 30 // Keep events for 30 days ) // Disable auto-refresh (opt-out, manual refresh only) AppFig.initialize( companyId: "acme-games", tenantId: "space-shooter", env: "prod", apiKey: "sk_live_abc123", autoRefresh: false // Must call refreshRules() manually ) ``` ### Logging Events ```swift AppFig.logEvent(name: String, parameters: [String: String]? = nil) ``` **Examples:** ```swift // Simple event AppFig.logEvent(name: "level_complete") // Event with parameters AppFig.logEvent(name: "purchase_made", parameters: [ "item_id": "sword_legendary", "price": "9.99", "currency": "USD" ]) // Screen view (auto-tracked by SDK too) AppFig.logScreenView(screenName: "main_menu", previousScreen: "settings") ``` ### Checking Features ```swift AppFig.isFeatureEnabled(_ feature: String) -> Bool AppFig.getFeatureValue(_ feature: String) -> String? ``` **Examples:** ```swift // Boolean check (returns true if value == "on") if AppFig.isFeatureEnabled("new_ui") { loadNewUI() } else { loadOldUI() } // Get actual value if let maxLives = AppFig.getFeatureValue("max_lives") { playerLives = Int(maxLives) ?? 3 } // Handle nil (no matching rules) if let bonus = AppFig.getFeatureValue("veteran_bonus") { applyBonus(bonus) // "2x", "1.5x", etc. } else { print("No bonus active") } ``` ### Setting Properties ```swift // User properties AppFig.setUserProperty(key: String, value: String) AppFig.removeUserProperty(key: String) // Device properties AppFig.setDeviceProperty(key: String, value: String) AppFig.removeDeviceProperty(key: String) // App version AppFig.setAppVersion(_ version: String) ``` **Examples:** ```swift // User properties AppFig.setUserProperty(key: "subscription_tier", value: "premium") AppFig.setUserProperty(key: "account_age_days", value: "30") AppFig.setUserProperty(key: "player_level", value: "15") // Device properties (most are auto-detected) AppFig.setAppVersion("1.2.3") AppFig.setDeviceProperty(key: "graphics_quality", value: "high") // Remove properties AppFig.removeUserProperty(key: "subscription_tier") ``` ### Auto-Detected Device Properties These are automatically set by the SDK on initialization: ``` platform "iOS", "iPadOS" os_version "17.0", "16.5", "15.0" language "English", "Japanese", "Spanish" timezone "America/Los_Angeles", "Asia/Tokyo" country "US", "JP", "GB" (requires internet on first run) device_brand "Apple" device_model "iPhone 15 Pro", "iPad Air", "iPhone SE" ``` ### Session Tracking Automatically tracked: ```swift // These events are logged automatically: "first_open" // First time app opens (persisted in UserDefaults) "session_start" // App comes to foreground "session_end" // App goes to background or 10 minutes of inactivity "screen_view" // When you call logScreenView() ``` ### Manual Refresh ```swift AppFig.refreshRules() // Manually reload rules from CDN ``` **Example:** ```swift // Manually refresh rules (useful for pull-to-refresh) AppFig.refreshRules() ``` **Note:** `setAutoRefresh()` and `setPollInterval()` are deprecated. Use the `autoRefresh` and `pollInterval` parameters in `initialize()` instead. ### Feature Reset (Recurring Triggers) ```swift AppFig.resetFeature(_ featureName: String) AppFig.resetAllFeatures() ``` Reset a feature's cached value and force re-evaluation. Useful for implementing recurring triggers like "show popup every 3 events". **Example:** ```swift // Check if feature is enabled if AppFig.isFeatureEnabled("level_complete_popup") { showPopup(message: "You've completed 3 levels!") // Reset so it triggers again after next 3 events AppFig.resetFeature("level_complete_popup") } // With event logging func onLevelComplete(level: Int) { AppFig.logEvent(name: "level_complete", parameters: ["level": String(level)]) // Check for milestone reward if AppFig.isFeatureEnabled("milestone_reward") { showReward() AppFig.resetFeature("milestone_reward") } } ``` **Use Cases:** - Show popup every N events (e.g., every 3 level completions) - Recurring promotions after X purchases - Periodic reward unlocks - Time-based feature re-triggers See [Feature Reset Guide](../../SDKs/FEATURE_RESET_GUIDE.md) for detailed examples. ### Debugging ```swift AppFig.hasRulesLoaded() -> Bool AppFig.getEventHistoryStats() -> [String: Any] ``` **Example:** ```swift if AppFig.hasRulesLoaded() { print("Rules are loaded") } let stats = AppFig.getEventHistoryStats() print("Event count: \(stats["count"] ?? 0)") print("Size: \(stats["sizeMB"] ?? 0) MB") ``` ## SwiftUI Integration ### App Entry Point ```swift import SwiftUI @main struct MyApp: App { init() { // Initialize AppFig AppFig.initialize( companyId: "acme-games", tenantId: "my-app", env: "prod", apiKey: "sk_live_abc123", autoRefresh: true ) } var body: some Scene { WindowGroup { ContentView() } } } ``` ### Feature Wrapper ```swift struct FeatureView: View { let featureName: String let content: Content init(_ featureName: String, @ViewBuilder content: () -> Content) { self.featureName = featureName self.content = content() } var body: some View { if AppFig.isFeatureEnabled(featureName) { content } } } // Usage struct ContentView: View { var body: some View { VStack { Text("Welcome!") FeatureView("premium_banner") { PremiumBanner() } } } } ``` ## Best Practices ### 1. Initialize Early Initialize in AppDelegate or App struct: ```swift @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { AppFig.initialize( companyId: "company", tenantId: "tenant", env: "prod", apiKey: "api-key", autoRefresh: true ) return true } } ``` ### 2. Cache Feature Values ```swift // ❌ Bad: Checks every frame override func draw(_ rect: CGRect) { if AppFig.isFeatureEnabled("double_xp") { // ... } } // ✅ Good: Check once, store result private lazy var hasDoubleXP = AppFig.isFeatureEnabled("double_xp") override func draw(_ rect: CGRect) { if hasDoubleXP { // ... } } ``` ### 3. Handle Nil Values ```swift let maxLives = Int(AppFig.getFeatureValue("max_lives") ?? "5") ?? 5 ``` ### 4. Log Events Liberally ```swift func completeLevel(_ level: Int, stars: Int, timeSeconds: Int) { AppFig.logEvent(name: "level_complete", parameters: [ "level_number": "\(level)", "time_seconds": "\(timeSeconds)", "stars": "\(stars)" ]) } ``` ## Troubleshooting ### "Framework not found: AppFig" **Problem:** Xcode can't find the AppFig framework **Solutions:** 1. Verify the AppFigSDK package (or `AppFigSDK.xcframework`) is in your project navigator 2. Check "Embed & Sign" is selected in Frameworks, Libraries, and Embedded Content 3. Clean build folder (Product → Clean Build Folder) 4. Restart Xcode ### Code signing issues **Problem:** "Code signing failed" or "Framework not properly signed" **Solutions:** 1. Ensure "Embed & Sign" is selected (not "Embed Without Signing") 2. Verify your provisioning profile includes framework embedding 3. Check code signing settings in Build Settings ### "AppFig not initialized" **Problem:** Calling SDK methods before `initialize()` **Solution:** ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { AppFig.initialize(...) // Must be first! AppFig.logEvent(name: "app_open") // Now OK return true } ``` ### Feature always returns nil **Problem:** No rules match for this feature **Solutions:** 1. Check feature name spelling (case-sensitive) 2. Verify rules are loaded: `AppFig.hasRulesLoaded()` 3. Log relevant events/properties before checking feature 4. Check console for AppFig debug messages ### Rules not updating **Problem:** Changes in dashboard not reflected in app **Solutions:** 1. Enable auto-refresh in `initialize()` with desired poll interval 2. Call `AppFig.refreshRules()` manually 3. Check console for AppFig messages 4. Verify internet connection ## Performance Tips ### Event History Management The SDK automatically manages event history to maintain optimal performance. Events are automatically trimmed based on: - Maximum event count (default: 5000) - Maximum event age (default: 7 days) ### Memory and CPU Usage AppFig has minimal memory and CPU overhead: - Low memory footprint suitable for mobile devices - Fast feature checks with intelligent caching - Efficient rule evaluation ## Next Steps - **[Rule Schema](https://appfig.com/docs/rule-schema)** - All rule options - **[Testing Guide](https://appfig.com/docs/testing)** - Test your features --- # Installing the SDKs Source: https://appfig.com/docs/package-manager-setup How to add AppFig to your project on each platform. The SDKs are published at [github.com/smartconfigui/AppFig-SDKs](https://github.com/smartconfigui/AppFig-SDKs); the current version is **2.5.0**. ## iOS Minimum: iOS 12. ### Swift Package Manager 1. In Xcode: **File > Add Package Dependencies** 2. Enter the URL: ``` https://github.com/smartconfigui/AppFig-SDKs ``` 3. Choose version `2.5.0` or later and add the **AppFigSDK** library to your app target. ### CocoaPods Add to your `Podfile`, then run `pod install`: ```ruby pod 'AppFigSDK', :git => 'https://github.com/smartconfigui/AppFig-SDKs.git', :tag => 'v2.5.0' ``` The pod is installed from the Git repository; it is not on the CocoaPods trunk, so `pod 'AppFigSDK'` without `:git` will not find it. ### Import ```swift import AppFigSDK ``` The class you call is `AppFig`; the module you import is `AppFigSDK`. ### Updating from 2.0.0 or earlier with a manually added framework The framework was renamed from `AppFig.xcframework` to `AppFigSDK.xcframework` so that its name matches its module. If you added the framework to Xcode by hand, remove the old one and add `ios/AppFigSDK.xcframework`. Your code does not change. ## Android Minimum: Android 5.0 (API 21). 1. Add the dependency to your app module (`build.gradle`): ```gradle dependencies { implementation 'com.appfig:appfig-android:2.5.0' } ``` In `build.gradle.kts`: `implementation("com.appfig:appfig-android:2.5.0")`. 2. Import: ```kotlin import com.appfig.sdk.AppFig ``` The SDK is on Maven Central, which a standard Android project already has in its repositories (`mavenCentral()`). Projects that installed it from JitPack (`com.github.smartconfigui:AppFig-SDKs`) keep working; use one or the other, not both. The libraries the SDK needs (OkHttp, Gson, the Kotlin standard library) are pulled in automatically. ## Flutter Minimum: Android 5.0 (API 21), iOS 12. Add to `pubspec.yaml`: ```yaml dependencies: appfig_flutter: git: url: https://github.com/smartconfigui/AppFig-SDKs.git path: flutter ref: v2.5.0 ``` ```dart import 'package:appfig_flutter/appfig_flutter.dart'; await AppFig.init(companyId: 'your-company', tenantId: 'your-app', env: 'prod', apiKey: 'your-api-key'); final value = await AppFig.getFeatureValue('my_feature'); ``` The package uses the native Android and iOS SDKs underneath, so nothing else has to be added to the Android or iOS projects. It is installed from Git; it is not on pub.dev. ## Unity Minimum: Unity 2021.3. In Unity: **Window > Package Manager > + > Add package from git URL**, then enter: ``` https://github.com/smartconfigui/AppFig-SDKs.git?path=/unity#v2.5.0 ``` The tag at the end pins the version; change it to update. The same address works as a line in `Packages/manifest.json`: `"com.appfig.sdk": ""`. The SDK works in Mono and IL2CPP builds, including with Managed Stripping Level set to High. On older Unity versions, download `unity/AppFigUnitySDK.dll` from the [SDK repository](https://github.com/smartconfigui/AppFig-SDKs/tree/v2.5.0/unity) and place it in `Assets/Plugins/AppFig/` instead. See the [Unity guide](https://appfig.com/docs/unity-integration). ## React / Web Download `react/AppFigReactSDK.js` and `react/AppFigReactSDK.d.ts` from the [SDK repository](https://github.com/smartconfigui/AppFig-SDKs/tree/main/react) and add them to your project: ```typescript import AppFig from './AppFigReactSDK'; ``` See the [React/Web guide](https://appfig.com/docs/react-web-guide). ## Next Steps - **[iOS Integration](https://appfig.com/docs/ios-integration)** - **[Android Integration](https://appfig.com/docs/android-integration)** - **[Unity Integration](https://appfig.com/docs/unity-integration)** - **[React/Web Guide](https://appfig.com/docs/react-web-guide)** --- # React/Web SDK Guide Source: https://appfig.com/docs/react-web-guide Complete guide to integrating AppFig into your React or web application. ## Installation > **SDK Download Repository:** [https://github.com/smartconfigui/AppFig-SDKs](https://github.com/smartconfigui/AppFig-SDKs) **Requirements:** Modern browser with ES6+ support (Chrome 90+, Firefox 88+, Safari 14+, Edge 90+) ### Step 1: Download the SDK Download the SDK files from: ``` https://github.com/smartconfigui/AppFig-SDKs/tree/v2.5.0/react ``` You'll need: - `AppFigReactSDK.js` (required) - Minified SDK bundle - `AppFigReactSDK.d.ts` (required) - TypeScript type definitions ### Step 2: Add to Your Project Copy both files to your project directory (e.g., `src/lib/appfig/`). ### Step 3: Import in Your Code ```typescript import AppFig from './lib/appfig/AppFigReactSDK.js'; ``` **TypeScript Support:** If you copied `AppFigReactSDK.d.ts` to the same folder, TypeScript will automatically discover the type definitions. No additional configuration needed. **Bundler Compatibility:** The minified bundle works with all modern bundlers: - ✅ Vite - ✅ Webpack - ✅ Rollup - ✅ Parcel - ✅ Create React App **Benefits:** - No npm installation required - No build steps - No dependency conflicts - No version management hassles - Works in any JavaScript/TypeScript project ## Quick Start ```typescript import AppFig from './AppFigReactSDK'; // Initialize with your credentials (auto-refresh enabled by default) await AppFig.init({ companyId: 'your-company-id', tenantId: 'your-tenant-id', env: 'prod', // 'dev' or 'prod' apiKey: 'your-api-key', autoRefresh: true, // Auto-refresh rules (default: true) ✨ NEW pollInterval: 3600000, // 1 hour (default: follows your plan) debugMode: false, // Enable debug logging (default: false) ✨ NEW sessionTimeoutMs: 1800000, // 30 minutes (default: 30 min) ✨ NEW maxEvents: 5000, // Max events to store (default: 5000) maxEventAgeDays: 7 // Max event age in days (default: 7) }); // Log events AppFig.logEvent('button_clicked', { button_id: 'upgrade', page: 'home' }); // Check features const welcomeMsg = AppFig.getConfig('welcome_message'); const showPremium = AppFig.getConfig('show_premium_banner'); if (showPremium === 'on') { showPremiumFeatures(); } ``` ## When to Do What: Timing Guide Understanding WHEN to call each SDK method is crucial for proper React/Web integration: | Action | When to Call | Where to Place | Code Example | |--------|-------------|----------------|--------------| | **Initialize SDK** | Once at app startup | main.tsx or App.tsx top-level | `await AppFig.init(...)` | | **Log Events** | Immediately after user action | Event handlers, onClick | `AppFig.logEvent('button_click')` | | **Set User Properties** | Once at login, when value changes | Auth callback, state change | `AppFig.setUserProperties({ tier: 'premium' })` | | **Evaluate Features** | When component mounts or renders | useEffect, component render | `AppFig.getConfig('feature_name')` | | **Apply Features** | Immediately after evaluation | Same render cycle | `if (value) return ` | | **Refresh Rules** | On demand (auto-refresh handles this) | Manual: Settings page | `AppFig.refreshRules()` | ### Complete Lifecycle Example ```typescript import React, { useEffect, useState } from 'react'; import AppFig from './AppFigReactSDK'; // 1. INITIALIZE: Once at app startup (main.tsx or App.tsx) async function initializeApp() { await AppFig.init({ companyId: 'your-company-id', tenantId: 'your-tenant-id', env: 'prod', apiKey: 'your-api-key' }); // 2. TRACK: Log app open AppFig.logEvent('app_open'); } // Call initialization initializeApp(); function App() { const [showWelcome, setShowWelcome] = useState(false); const [playerLives, setPlayerLives] = useState(3); useEffect(() => { // 3. EVALUATE: Check features when component mounts checkWelcomeBonus(); configureGameSettings(); }, []); const checkWelcomeBonus = () => { // Evaluate right before using const bonusValue = AppFig.getConfig('welcome_bonus'); // 4. APPLY: Update state immediately if (bonusValue === 'on') { setShowWelcome(true); } }; const configureGameSettings = () => { // Evaluate with fallback const maxLives = parseInt(AppFig.getConfig('max_lives') || '3'); // Apply to state setPlayerLives(maxLives); }; const handleLevelComplete = () => { // TRACK: Log immediately after action AppFig.logEvent('level_complete', { level: currentLevel.toString() }); // Re-evaluate features that depend on level checkNewUnlocks(); }; const handleSubscriptionPurchase = (tier: string) => { // Update property when it changes AppFig.setUserProperties({ subscription_tier: tier }); // Re-evaluate premium features updatePremiumFeatures(); }; return (
{showWelcome && }
Lives: {playerLives}
); } ``` ### Timing Best Practices #### Initialize Once at Startup ```typescript // ✅ CORRECT: Initialize in main.tsx before rendering import AppFig from './AppFigReactSDK'; await AppFig.init({ companyId: '...', tenantId: '...', env: 'prod', apiKey: '...' }); const root = ReactDOM.createRoot(document.getElementById('root')!); root.render(); // ❌ WRONG: Don't initialize in every component function MyComponent() { useEffect(() => { AppFig.init({...}); // Bad! SDK already initialized }, []); } ``` #### Log Events Immediately ```typescript // ✅ CORRECT: Log right when action happens const handlePurchaseClick = () => { AppFig.logEvent('purchase_initiated', { item_id: 'premium_plan' }); showPurchaseDialog(); }; // ❌ WRONG: Don't batch events const pendingEvents: string[] = []; const handleClick = () => { pendingEvents.push('button_clicked'); // Bad! }; ``` #### Cache Feature Values with State ```typescript // ✅ CORRECT: Check once and cache in state function GameComponent() { const [hasDoubleXP, setHasDoubleXP] = useState(false); useEffect(() => { const doubleXP = AppFig.getConfig('double_xp') === 'on'; setHasDoubleXP(doubleXP); }, []); const calculateXP = (baseXP: number) => { return hasDoubleXP ? baseXP * 2 : baseXP; }; return
XP: {calculateXP(100)}
; } // ❌ WRONG: Don't check on every render function BadComponent() { // This checks on every single render - very inefficient! const hasDoubleXP = AppFig.getConfig('double_xp') === 'on'; return
Has XP: {hasDoubleXP}
; } ``` #### Evaluate in useEffect, Not Render ```typescript // ✅ CORRECT: Evaluate in useEffect function WelcomeScreen() { const [showBonus, setShowBonus] = useState(false); useEffect(() => { const bonusEnabled = AppFig.getConfig('welcome_bonus') === 'on'; setShowBonus(bonusEnabled); }, []); return (
{showBonus && }
); } // ❌ WRONG: Don't evaluate in render without memoization function BadWelcomeScreen() { // This evaluates on every render const showBonus = AppFig.getConfig('welcome_bonus') === 'on'; return (
{showBonus && }
); } ``` --- ## API Reference ### Initialization ```typescript await AppFig.init({ companyId: string, // Required: Your company ID tenantId: string, // Required: Your tenant/project ID env: 'dev' | 'prod', // Required: Environment apiKey: string, // Required: Your API key autoRefresh?: boolean, // Optional: Auto-refresh rules (default: true) ✨ NEW DEFAULT pollInterval?: number, // Optional: leave out to follow your plan debugMode?: boolean, // Optional: Enable debug logging (default: false) ✨ NEW sessionTimeoutMs?: number, // Optional: Session timeout (default: 1800000 = 30 min) ✨ NEW maxEvents?: number, // Optional: Max events to store (default: 5000, max: 100000) maxEventAgeDays?: number, // Optional: Max event age in days (default: 7, max: 365) cdnBaseUrl?: string, // Optional: rules host (default: production) 🆕 2.3 // Deprecated (use autoRefresh instead): autoUpdate?: boolean // Deprecated: Use autoRefresh instead }) ``` **Parameters:** - `companyId` (required) - Your company ID from AppFig dashboard - `tenantId` (required) - Your tenant/project ID from AppFig dashboard - `env` (required) - Environment: `'dev'` or `'prod'` - `apiKey` (required) - Your API key from AppFig dashboard - `autoRefresh` (optional) - Enable automatic rule refreshing (default: **true**) ⚠️ **Breaking Change** - `pollInterval` (optional) - Auto-refresh interval in milliseconds. Leave it out and the SDK checks for changes every minute, on every plan 🆕 **New in 2.3**. A value you set is kept, but never faster than your plan allows. - `debugMode` (optional) - Enable debug console logs (default: false) 🆕 **New in v2.0** - `sessionTimeoutMs` (optional) - Session timeout in milliseconds (default: 1800000 = 30 min, range: 60000-7200000) 🆕 **New in v2.0** - `maxEvents` (optional) - Maximum events to store locally (100-100000, default: 5000) - `maxEventAgeDays` (optional) - Maximum age of events in days (1-365, default: 7) - `cdnBaseUrl` (optional) - The rules host to read from, e.g. `https://rules-stage.appfig.com` for a staging build. Leave it out for production (`https://rules-prod.appfig.com`). Must start with `https://`. 🆕 **New in 2.3** - `autoUpdate` (deprecated) - Use `autoRefresh` instead (backward compatibility maintained) **Examples:** ```typescript // Basic initialization (auto-refresh enabled by default) await AppFig.init({ companyId: 'acme-games', tenantId: 'space-shooter', env: 'prod', apiKey: 'sk_live_abc123xyz' }); // With custom settings await AppFig.init({ companyId: 'acme-games', tenantId: 'space-shooter', env: 'prod', apiKey: 'sk_live_abc123xyz', autoRefresh: true, // Explicit (but this is already the default) pollInterval: 3600000, // 1 hour debugMode: true, // See what's happening sessionTimeoutMs: 900000, // 15 minutes instead of 30 maxEvents: 10000 // Store more events }); // Disable auto-refresh (opt-out) await AppFig.init({ companyId: 'acme-games', tenantId: 'space-shooter', env: 'prod', apiKey: 'sk_live_abc123xyz', autoRefresh: false // Manual refresh only }); ``` ### Logging Events ```typescript AppFig.logEvent(name: string, params?: Record) ``` **Examples:** ```typescript // Simple event AppFig.logEvent('page_view'); // Event with parameters AppFig.logEvent('purchase_completed', { item_id: 'premium_plan', price: 29.99, currency: 'USD' }); // Button click AppFig.logEvent('button_clicked', { button_id: 'cta', page: 'landing', variant: 'blue' }); ``` ### Checking Features ```typescript AppFig.getConfig(flagName: string): any ``` Returns the feature value, or `null` if no rules match. **Examples:** ```typescript // Get feature value const welcomeMsg = AppFig.getConfig('welcome_message'); if (welcomeMsg) { setMessage(welcomeMsg); } // Boolean features const showPremium = AppFig.getConfig('show_premium_banner'); if (showPremium === 'on') { renderPremiumBanner(); } // Numeric features const maxRetries = AppFig.getConfig('max_api_retries'); const retries = parseInt(maxRetries || '3', 10); // Complex features const pricingConfig = AppFig.getConfig('pricing_tiers'); // Returns: { basic: 9, pro: 29, enterprise: 99 } ``` ### Setting Properties ```typescript // User properties AppFig.setUserProperties(props: Record) // Device properties AppFig.setDeviceProperties(props: Record) // App version AppFig.setAppVersion(version: string) ``` **Examples:** ```typescript // Set user properties AppFig.setUserProperties({ subscription_tier: 'premium', account_age_days: 45, preferred_theme: 'dark' }); // Set device properties AppFig.setDeviceProperties({ browser_name: 'Chrome', screen_width: 1920 }); // Set app version AppFig.setAppVersion('2.1.0'); ``` ### Auto-Detected Properties These are automatically set by the SDK on initialization: ```javascript country "US", "JP", "GB" (from CDN response headers) platform "macOS", "Windows", "Linux", "iOS", "Android" language "en-US", "ja", "es-ES" (from browser) timezone "America/Los_Angeles", "Asia/Tokyo" (from system) os_version "10.15.7", "11.0", "14.2" (from user agent) device_brand "Apple", "Microsoft", "Google" device_model "Chrome 120 on macOS", "Firefox 121 on Windows" app_version "1.0.0" (you set this with setAppVersion()) sdk_version "2.0.0" (AppFig SDK version) ``` **Country Detection:** - Primary: Extracted from CDN response `Country` header (Cloudflare Workers) - Fallback: Static endpoint `rules-dev.appfig.com` with 5-second timeout - No third-party services used (fully controlled by AppFig infrastructure) ### Manual Refresh ```typescript await AppFig.refreshRules() AppFig.stopAutoRefresh() ``` **Examples:** ```typescript // Manually refresh rules await AppFig.refreshRules(); // Stop auto-refresh AppFig.stopAutoRefresh(); ``` ### Feature Reset (Recurring Triggers) ```typescript AppFig.resetFeature(featureName: string) AppFig.resetAllFeatures() ``` Reset a feature's cached value and force re-evaluation. Useful for implementing recurring triggers like "show popup every 3 events". **Example:** ```typescript // Check if feature is enabled if (AppFig.check("level_complete_popup")) { showPopup("You've completed 3 levels!"); // Reset so it triggers again after next 3 events AppFig.resetFeature("level_complete_popup"); } // With event logging function onLevelComplete(level: number) { AppFig.logEvent("level_complete", { level: level.toString() }); // Check for milestone reward if (AppFig.check("milestone_reward")) { showReward(); AppFig.resetFeature("milestone_reward"); } } ``` **Use Cases:** - Show popup every N events (e.g., every 3 level completions) - Recurring promotions after X purchases - Periodic reward unlocks - Time-based feature re-triggers See [Feature Reset Guide](../../SDKs/FEATURE_RESET_GUIDE.md) for detailed examples. ### Debugging ```typescript AppFig.getDebugInfo() AppFig.getEventHistory() ``` **Example:** ```typescript const debug = AppFig.getDebugInfo(); console.log('Rules:', debug.rules); console.log('Events:', debug.events); console.log('User properties:', debug.userProperties); console.log('Device properties:', debug.deviceProperties); console.log('Cached results:', debug.cachedResults); const events = AppFig.getEventHistory(); console.log(`Logged ${events.length} events`); ``` ## React Integration ### Basic Setup ```typescript import { useEffect, useState } from 'react'; import AppFig from './AppFigReactSDK'; function App() { const [isInitialized, setIsInitialized] = useState(false); const [welcomeMessage, setWelcomeMessage] = useState(''); useEffect(() => { async function init() { await AppFig.init({ companyId: 'acme-games', tenantId: 'my-app', env: 'prod', apiKey: 'sk_live_abc123' }); setIsInitialized(true); // Get initial feature values const msg = AppFig.getConfig('welcome_message'); setWelcomeMessage(msg || 'Welcome!'); } init(); }, []); if (!isInitialized) { return
Loading...
; } return (

{welcomeMessage}

); } ``` ### Custom Hook ```typescript import { useState, useEffect } from 'react'; import AppFig from './AppFigReactSDK'; export function useFeature(featureName: string) { const [value, setValue] = useState(null); useEffect(() => { const val = AppFig.getConfig(featureName); setValue(val); }, [featureName]); return value; } // Usage function MyComponent() { const showBanner = useFeature('premium_banner'); const maxRetries = useFeature('api_max_retries'); return (
{showBanner === 'on' && }
); } ``` ### Context Provider ```typescript import React, { createContext, useContext, useEffect, useState } from 'react'; import AppFig from './AppFigReactSDK'; const AppFigContext = createContext<{ isInitialized: boolean; getFeature: (name: string) => any; logEvent: (name: string, params?: any) => void; }>({ isInitialized: false, getFeature: () => null, logEvent: () => {} }); export function AppFigProvider({ children, companyId, tenantId, env, apiKey }: { children: React.ReactNode; companyId: string; tenantId: string; env: 'dev' | 'prod'; apiKey: string; }) { const [isInitialized, setIsInitialized] = useState(false); useEffect(() => { async function init() { await AppFig.init({ companyId, tenantId, env, apiKey }); setIsInitialized(true); } init(); }, [companyId, tenantId, env, apiKey]); const value = { isInitialized, getFeature: (name: string) => AppFig.getConfig(name), logEvent: (name: string, params?: any) => AppFig.logEvent(name, params) }; return ( {children} ); } export function useAppFig() { return useContext(AppFigContext); } // Usage function App() { return ( ); } function MyComponent() { const { isInitialized, getFeature, logEvent } = useAppFig(); if (!isInitialized) { return
Loading...
; } const showBanner = getFeature('premium_banner'); return (
{showBanner === 'on' && }
); } ``` ## Automatic Tracking The SDK automatically tracks these events: ```typescript 'first_open' // First time user visits (persisted in localStorage) 'session_start' // Page becomes visible 'session_end' // Page hidden or 10 min inactivity 'screen_view' // URL changes (single-page apps) ``` ### Screen View Tracking Automatically tracks navigation in single-page apps: ```typescript // Automatically logged when URL changes // Works with: // - History API (pushState, replaceState) // - Hash changes (#/page) // - Browser back/forward buttons // Each screen view includes: AppFig.logEvent('screen_view', { screen_name: 'dashboard', // From URL path or hash previous_screen: 'home' // Previous screen }); ``` ## Debug Mode Enable debug logging to see detailed SDK activity: ```typescript await AppFig.init({ companyId: 'acme-games', tenantId: 'my-app', env: 'prod', apiKey: 'sk_live_abc123', debugMode: true // ← Enable debug logs }); // Console output: // [AppFig] 📱 Detected platform: macOS // [AppFig] 🌍 Detected language: en-US // [AppFig] 🔧 Device properties set: country, platform, language // [AppFig] ✅ Loaded rules from CDN - Feature count: 5 // [AppFig] 🔍 getConfig called for: welcome_message // [AppFig] 🔍 Returning CACHED result for welcome_message: "Hello!" ``` ## Best Practices ### 1. Initialize Once Initialize at app entry point: ```typescript // ✅ Good: Initialize in root component function App() { useEffect(() => { AppFig.init({ companyId: 'acme-games', tenantId: 'my-app', env: 'prod', apiKey: 'sk_live_abc123' }); }, []); // ... } // ❌ Bad: Initializing in multiple places function Header() { useEffect(() => { AppFig.init({ ... }); // Don't repeat! }, []); } ``` ### 2. Cache Feature Values in State ```typescript // ✅ Good: Check once, store in state function Component() { const [showBanner, setShowBanner] = useState(false); useEffect(() => { const value = AppFig.getConfig('show_banner'); setShowBanner(value === 'on'); }, []); return showBanner ? : null; } // ❌ Bad: Checking on every render function Component() { const showBanner = AppFig.getConfig('show_banner') === 'on'; return showBanner ? : null; } ``` ### 3. Handle Null Values ```typescript // ✅ Good: Provide fallback const maxRetries = parseInt( AppFig.getConfig('max_retries') || '3', 10 ); // ❌ Bad: No fallback const maxRetries = parseInt(AppFig.getConfig('max_retries'), 10); // NaN if feature returns null! ``` ### 4. Log Events Generously ```typescript function handlePurchase(item: string, price: number) { // Log detailed events AppFig.logEvent('purchase_started', { item_id: item, price: price.toString(), currency: 'USD', page: window.location.pathname }); // ... process purchase ... AppFig.logEvent('purchase_completed', { item_id: item, price: price.toString(), payment_method: 'stripe' }); } ``` ## TypeScript Types ```typescript import type { AppFigRule, AppFigInitParams, AppFigEvent, Condition } from './AppFigReactSDK'; // Use types in your code const params: AppFigInitParams = { companyId: 'acme-games', tenantId: 'my-app', env: 'prod', apiKey: 'sk_live_abc123', debugMode: true }; ``` ## Performance Tips ### Caching Features are cached after first evaluation for optimal performance: ```typescript // First call: Evaluates rules const msg1 = AppFig.getConfig('welcome_message'); // Second call: Returns cached value (nearly instant) const msg2 = AppFig.getConfig('welcome_message'); ``` Cache is invalidated when: - New events are logged - User/device properties change - Rules are refreshed ### Bundle Size The SDK has a small footprint suitable for web applications, with minimal impact on your application's bundle size after minification and compression. ## Troubleshooting ### Module not found or import errors **Problem:** Bundler can't find the SDK file **Solutions:** 1. Verify `AppFigReactSDK.js` is in the correct location 2. Check import path is correct (use relative path like `'./lib/appfig/AppFigReactSDK.js'`) 3. For Webpack/CRA: Ensure path starts with `./` or `../` 4. For Vite: Import path should work as-is ### TypeScript errors: "Could not find a declaration file" **Problem:** TypeScript shows type errors **Solutions:** 1. Verify `AppFigReactSDK.d.ts` is in the same folder as `AppFigReactSDK.js` 2. If using a different location, add `/// ` at the top of your file 3. Or use `// @ts-ignore` above the import if types aren't needed ### Rules not loading **Problem:** `Failed to load rules from CDN` **Solutions:** 1. Verify API key is correct 2. Check browser console for network errors 3. Ensure company ID and tenant ID are correct 4. Verify environment ('dev' or 'prod') matches your dashboard setup ### Features always return null **Problem:** No rules match **Solutions:** 1. Verify feature name spelling (case-sensitive) 2. Check rules are loaded: `AppFig.getDebugInfo().rules` 3. Log relevant events/properties before checking feature 4. Enable debug mode to see rule evaluation ### Auto-refresh not working **Problem:** Changes in dashboard not reflected **Solutions:** 1. Verify `autoUpdate: true` in initialization 2. Wait for the refresh interval (one minute) 3. Check browser console for refresh logs 4. Call `AppFig.refreshRules()` manually ## Next Steps - **[Rule Schema](https://appfig.com/docs/rule-schema)** - All rule options - **[Testing Guide](https://appfig.com/docs/testing)** - Test your features --- # Unity SDK Integration Guide Source: https://appfig.com/docs/unity-integration Complete guide to integrating AppFig into your Unity project. ## Installation > **SDK Download Repository:** [https://github.com/smartconfigui/AppFig-SDKs](https://github.com/smartconfigui/AppFig-SDKs) **Requirements:** Unity 2021.3+ for the Package Manager install, Unity 2019.4+ with the DLL (supports all platforms: iOS, Android, Windows, macOS, Linux, WebGL) ### Step 1: Add the package In Unity: **Window > Package Manager > + > Add package from git URL**, then enter: ``` https://github.com/smartconfigui/AppFig-SDKs.git?path=/unity#v2.5.0 ``` The tag at the end pins the version; change it to update. **That's it!** No additional configuration needed. The SDK works in Mono and IL2CPP builds, including with Managed Stripping Level set to High. ### Alternative: copy the DLL (older Unity versions) 1. Download `AppFigUnitySDK.dll` from `https://github.com/smartconfigui/AppFig-SDKs/tree/v2.5.0/unity` 2. In Unity, create the folder structure: `Assets/Plugins/AppFig/` 3. Drag `AppFigUnitySDK.dll` into that folder. Unity detects the assembly automatically. Use one way or the other, not both: two copies of the assembly do not compile. ### What's Included The single DLL contains all SDK functionality: - **Core SDK** - `AppFig` class with all feature flag and event methods - **AppFigHelper** - Optional- MonoBehaviour wrapper for Inspector-based setup - **AppFigApplier** - Optional- No-code component for applying feature values to GameObjects - **AppFigABTester** - Optional- Visual A/B testing component No meta files, no dependencies, no build steps required. ## Quick Start ### Initialize Initialize with your company credentials: ```csharp using UnityEngine; public class GameManager : MonoBehaviour { void Start() { // Initialize SDK AppFig.Init( companyId: "your-company-id", tenantId: "your-tenant-id", env: "prod", // "dev" or "prod" apiKey: "your-api-key" ); // Log events AppFig.LogEvent("app_open"); // Check features if (AppFig.IsFeatureEnabled("double_xp")) { ApplyDoubleXP(); } string maxLives = AppFig.GetFeatureValue("max_lives"); int lives = int.Parse(maxLives); } } ``` ## When to Do What: Timing Guide Understanding WHEN to call each SDK method is crucial for proper implementation. Follow this guide to ensure optimal integration: | Action | When to Call | Where to Place | Code Example | |--------|-------------|----------------|--------------| | **Initialize SDK** | Once at app startup, before any SDK calls | `GameManager.Start()` or `Awake()` | `AppFig.Init(...)` | | **Log Events** | Immediately after user action | Event handlers, button callbacks | `AppFig.LogEvent("level_complete")` | | **Set User Properties** | Once at login, when value changes | Auth callback, state change | `AppFig.SetUserProperty("tier", "premium")` | | **Set Device Properties** | Once at startup (usually auto-detected) | `Start()` method | `AppFig.SetAppVersion("1.0.0")` | | **Evaluate Features** | Right before you need the value | Decision points, scene load | `AppFig.GetFeatureValue("max_lives")` | | **Apply Features** | Immediately after evaluation | Same method as evaluation | `if (value) { ShowUI(); }` | | **Refresh Rules** | On demand or periodically (auto-refresh handles this) | Manual: Settings screen | `AppFig.RefreshRules()` | ### Detailed Timing Scenarios #### Initialization Timing ```csharp public class GameManager : MonoBehaviour { void Awake() { // ✅ CORRECT: Initialize once at startup // This ensures SDK is ready before any other code runs AppFig.Init("company-id", "tenant-id", "prod", "api-key"); } void Start() { // ✅ Also acceptable: Initialize in Start() // Just ensure it happens before any SDK calls AppFig.Init("company-id", "tenant-id", "prod", "api-key"); } } // ❌ WRONG: Don't initialize in every scene public class LevelManager : MonoBehaviour { void Start() { AppFig.Init(...); // Bad! SDK already initialized } } // ❌ WRONG: Don't initialize multiple times void Update() { AppFig.Init(...); // Bad! Only initialize once } ``` #### Event Logging Timing ```csharp // ✅ CORRECT: Log immediately after action public void OnLevelComplete() { SaveProgress(); ShowCompletionUI(); // Log right when it happens AppFig.LogEvent("level_complete", new Dictionary { { "level_number", currentLevel.ToString() }, { "time_seconds", elapsedTime.ToString() } }); } // ✅ CORRECT: Log on button click public void OnPurchaseButtonClicked() { // Log the intention immediately AppFig.LogEvent("purchase_initiated"); ShowPurchaseDialog(); } // ❌ WRONG: Don't batch events private List pendingEvents = new List(); void OnLevelComplete() { pendingEvents.Add("level_complete"); // Bad! Log immediately } void OnApplicationQuit() { // Bad! Events should be logged as they happen foreach (var evt in pendingEvents) { AppFig.LogEvent(evt); } } // ❌ WRONG: Don't log in Update() void Update() { if (Input.GetKeyDown(KeyCode.Space)) { // Bad! Log in the actual event handler AppFig.LogEvent("space_pressed"); } } ``` #### Property Setting Timing ```csharp // ✅ CORRECT: Set once when value is established public void OnLoginSuccess(string userId, string tier) { // Set properties right after authentication AppFig.SetUserProperty("user_id", userId); AppFig.SetUserProperty("subscription_tier", tier); AppFig.SetUserProperty("login_date", DateTime.Now.ToString()); } // ✅ CORRECT: Update when value changes public void OnSubscriptionUpgrade(string newTier) { // Update property when it changes AppFig.SetUserProperty("subscription_tier", newTier); // Re-evaluate features that depend on tier UpdateUIBasedOnTier(); } // ❌ WRONG: Don't set repeatedly with same value void Update() { // Bad! Set once, not every frame AppFig.SetUserProperty("user_id", currentUserId); } // ❌ WRONG: Don't set before initialization void Awake() { AppFig.SetUserProperty("level", "1"); // Bad! Init first AppFig.Init(...); // Too late } ``` #### Feature Evaluation Timing ```csharp // ✅ CORRECT: Evaluate when you need the value public void LoadLevel(int levelNumber) { // Check feature right before using it string difficultyValue = AppFig.GetFeatureValue("difficulty_multiplier"); float difficulty = float.Parse(difficultyValue ?? "1.0"); // Apply immediately ApplyDifficultySettings(difficulty); LoadScene(levelNumber); } // ✅ CORRECT: Cache for performance private bool hasDoubleXP = false; void Start() { // Check once and cache the result hasDoubleXP = AppFig.IsFeatureEnabled("double_xp"); } void CalculateXP(int baseXP) { // Use cached value in hot path return hasDoubleXP ? baseXP * 2 : baseXP; } // ❌ WRONG: Don't check every frame void Update() { // Bad! Very inefficient if (AppFig.IsFeatureEnabled("double_xp")) { ApplyDoubleXP(); } } // ❌ WRONG: Don't check before logging relevant events void Start() { // Bad! Feature evaluates to null because no events logged yet if (AppFig.IsFeatureEnabled("veteran_bonus")) { } // Should log events first AppFig.LogEvent("app_open"); // Now this works if (AppFig.IsFeatureEnabled("veteran_bonus")) { } } ``` #### Feature Application Timing ```csharp // ✅ CORRECT: Apply immediately after evaluation void Start() { // Evaluate bool showBonus = AppFig.IsFeatureEnabled("welcome_bonus"); // Apply right away with null handling if (showBonus) { welcomeBonusPanel.SetActive(true); GrantCoins(500); } else { welcomeBonusPanel.SetActive(false); } } // ✅ CORRECT: Apply configuration values void LoadGameSettings() { // Evaluate with fallback string maxLivesStr = AppFig.GetFeatureValue("max_lives"); int maxLives = int.Parse(maxLivesStr ?? "3"); // Apply to game state playerMaxLives = maxLives; UpdateUI(); } // ❌ WRONG: Don't apply in different frame/context private string featureValue; void Start() { featureValue = AppFig.GetFeatureValue("theme"); } void Update() { // Bad! Apply immediately after evaluation if (featureValue == "dark") { ApplyDarkTheme(); } } // ❌ WRONG: Don't forget null handling void Start() { string maxLives = AppFig.GetFeatureValue("max_lives"); // Bad! What if maxLives is null? int lives = int.Parse(maxLives); // NullReferenceException! // Should be: int lives = int.Parse(maxLives ?? "3"); } ``` ### Complete Lifecycle Example Here's a complete example showing proper timing for all SDK operations: ```csharp using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; public class GameManager : MonoBehaviour { public GameObject welcomePanel; public Text livesText; private int playerLives = 3; // 1. INITIALIZE: Once at startup void Start() { AppFig.Init("company-id", "tenant-id", "prod", "api-key"); // 2. SET PROPERTIES: Once when known (device props are auto-detected) AppFig.SetAppVersion("1.0.0"); // 3. TRACK: Log events as they happen AppFig.LogEvent("app_open"); // 4. EVALUATE: When you need values CheckWelcomeBonus(); ConfigureGameSettings(); } void CheckWelcomeBonus() { // Evaluate right before using bool showWelcome = AppFig.IsFeatureEnabled("welcome_bonus"); // Apply immediately if (showWelcome) { welcomePanel.SetActive(true); } } void ConfigureGameSettings() { // Evaluate with fallback string maxLivesValue = AppFig.GetFeatureValue("max_lives"); playerLives = int.Parse(maxLivesValue ?? "3"); // Apply to UI livesText.text = $"Lives: {playerLives}"; } public void OnLevelComplete() { // Track immediately after action AppFig.LogEvent("level_complete", new Dictionary { { "level", currentLevel.ToString() } }); // Re-evaluate features that depend on level completion CheckNewUnlocks(); } public void OnSubscriptionPurchased(string tier) { // Update property when it changes AppFig.SetUserProperty("subscription_tier", tier); // Re-evaluate features that depend on subscription UpdatePremiumFeatures(); } } ``` --- ## API Reference ### Initialization ```csharp AppFig.Init( string companyId, // Required: Your company ID string tenantId, // Required: Your tenant/project ID string env, // Required: "dev" or "prod" string apiKey, // Required: Your API key bool autoRefresh = true, // Optional: Enable auto-refresh (default: true) ✨ NEW DEFAULT long pollInterval = 43200000, // Optional: leave out to follow your plan bool debugMode = false, // Optional: Enable debug logging (default: false) ✨ NEW long sessionTimeoutMs = 1800000, // Optional: 30 minutes (default: 30 min) ✨ NEW int maxEvents = 5000, // Optional: Max events (default: 5000, max: 100000) int maxEventAgeDays = 7, // Optional: Max age in days (default: 7, max: 365) string cdnBaseUrl = null // Optional: rules host (default: production) 🆕 2.3 ) ``` **Parameters:** - `companyId` (required) - Your company ID from AppFig dashboard - `tenantId` (required) - Your tenant/project ID from AppFig dashboard - `env` (required) - Environment: `"dev"` or `"prod"` - `apiKey` (required) - Your API key from AppFig dashboard - `autoRefresh` (optional) - Enable automatic background rule updates (default: **true**) ⚠️ **Breaking Change** - `pollInterval` (optional) - Auto-refresh interval in milliseconds. Leave it out and the SDK checks for changes every minute, on every plan 🆕 **New in 2.3**. A value you set is kept, but never faster than your plan allows. - `debugMode` (optional) - Enable debug logging to Unity console (default: false) 🆕 **New in v2.0** - `sessionTimeoutMs` (optional) - Session timeout in milliseconds (default: 1800000 = 30 min, range: 60000-7200000) 🆕 **New in v2.0** - `maxEvents` (optional) - Maximum events to store in PlayerPrefs (100-100000, default: 5000) - `maxEventAgeDays` (optional) - Maximum age of events in days (1-365, default: 7) - `cdnBaseUrl` (optional) - The rules host to read from, e.g. `https://rules-stage.appfig.com` for a staging build. Leave it out for production (`https://rules-prod.appfig.com`). Must start with `https://`. 🆕 **New in 2.3** **Examples:** ```csharp // Basic initialization (auto-refresh enabled by default) AppFig.Init("acme-games", "space-shooter", "prod", "sk_live_abc123"); // With a fixed poll interval (1 hour) AppFig.Init( companyId: "acme-games", tenantId: "space-shooter", env: "prod", apiKey: "sk_live_abc123", autoRefresh: true, // Explicit (but this is already the default) pollInterval: 3600000 // 1 hour ); // With debug mode enabled (useful during development) AppFig.Init( companyId: "acme-games", tenantId: "space-shooter", env: "dev", // Use dev environment apiKey: "sk_test_abc123", autoRefresh: true, pollInterval: 600000, // 10 minutes for faster testing debugMode: true // See all SDK operations in console ); // With all parameters customized AppFig.Init( companyId: "acme-games", tenantId: "space-shooter", env: "prod", apiKey: "sk_live_abc123", autoRefresh: true, pollInterval: 3600000, debugMode: false, sessionTimeoutMs: 900000, // 15 minutes instead of 30 maxEvents: 10000, // Store more events maxEventAgeDays: 30 // Keep events for 30 days ); // Disable auto-refresh (opt-out, manual refresh only) AppFig.Init( companyId: "acme-games", tenantId: "space-shooter", env: "prod", apiKey: "sk_live_abc123", autoRefresh: false // Must call RefreshRules() manually ); ``` ### Logging Events ```csharp AppFig.LogEvent(string eventName) AppFig.LogEvent(string eventName, Dictionary parameters) ``` **Examples:** ```csharp // Simple event AppFig.LogEvent("level_complete"); // Event with parameters AppFig.LogEvent("purchase_made", new Dictionary { { "item_id", "sword_legendary" }, { "price", "9.99" }, { "currency", "USD" } }); // Screen view (auto-tracked by SDK too) AppFig.LogScreenView("main_menu", "settings"); ``` ### Checking Features ```csharp bool AppFig.IsFeatureEnabled(string featureName) string AppFig.GetFeatureValue(string featureName) ``` **Examples:** ```csharp // Boolean check (returns true if value == "on") if (AppFig.IsFeatureEnabled("new_ui")) { LoadNewUI(); } else { LoadOldUI(); } // Get actual value string maxLives = AppFig.GetFeatureValue("max_lives"); if (maxLives != null) { int lives = int.Parse(maxLives); playerLives = lives; } // Handle null (no matching rules) string bonus = AppFig.GetFeatureValue("veteran_bonus"); if (bonus == null) { Debug.Log("No bonus active"); } else { ApplyBonus(bonus); // "2x", "1.5x", etc. } ``` ### Setting Properties ```csharp // User properties AppFig.SetUserProperty(string key, string value) AppFig.RemoveUserProperty(string key) // Device properties AppFig.SetDeviceProperty(string key, string value) AppFig.RemoveDeviceProperty(string key) // App version (convenience method) AppFig.SetAppVersion(string version) ``` **Examples:** ```csharp // User properties AppFig.SetUserProperty("subscription_tier", "premium"); AppFig.SetUserProperty("account_age_days", "30"); AppFig.SetUserProperty("player_level", "15"); // Device properties (most are auto-detected, but you can add custom ones) AppFig.SetAppVersion("1.2.3"); AppFig.SetDeviceProperty("graphics_quality", "high"); // Remove properties AppFig.RemoveUserProperty("subscription_tier"); ``` ### Auto-Detected Device Properties These are automatically set by the SDK on initialization: ``` platform "iOS", "Android", "Windows", "macOS", "Linux", etc. os_version "17.0", "13", "11.0" language "English", "Japanese", "Spanish" timezone "America/Los_Angeles", "Asia/Tokyo" country "US", "JP", "GB" (requires internet on first run) device_brand "Apple", "Samsung", "Google", "Huawei" device_model "iPhone 15", "Galaxy S23", "Pixel 8" ``` Use these in your rules without any setup! ### Session Tracking Automatically tracked: ```csharp // These events are logged automatically: "first_open" // First time app opens (persisted in PlayerPrefs) "session_start" // App gains focus "session_end" // App loses focus or 10 minutes of inactivity "screen_view" // When you call LogScreenView() ``` ### Manual Refresh ```csharp AppFig.RefreshRules() // Manually reload rules from CDN ``` **Example:** ```csharp // Manually refresh rules (useful for testing rule changes) AppFig.RefreshRules(); ``` **Note:** `SetAutoRefresh()` and `SetPollInterval()` are deprecated. Use the `autoRefresh` and `pollInterval` parameters in `Init()` instead. ### Feature Reset (Recurring Triggers) ```csharp AppFig.ResetFeature(string featureName) AppFig.ResetAllFeatures() ``` Reset a feature's cached value and force re-evaluation. Useful for implementing recurring triggers like "show popup every 3 events". **Example:** ```csharp // Check if feature is enabled if (AppFig.IsFeatureEnabled("level_complete_popup")) { ShowPopup("You've completed 3 levels!"); // Reset so it triggers again after next 3 events AppFig.ResetFeature("level_complete_popup"); } // With event logging void OnLevelComplete(int level) { AppFig.LogEvent("level_complete", new Dictionary { { "level", level.ToString() } }); // Check for milestone reward if (AppFig.IsFeatureEnabled("milestone_reward")) { ShowReward(); AppFig.ResetFeature("milestone_reward"); } } ``` **Use Cases:** - Show popup every N events (e.g., every 3 level completions) - Recurring promotions after X purchases - Periodic reward unlocks - Time-based feature re-triggers See [Feature Reset Guide](../../SDKs/FEATURE_RESET_GUIDE.md) for detailed examples. ### Debugging ```csharp AppFig.GetDebugInfo() // Returns dict with rules, events, properties, cache ``` **Example:** ```csharp var debug = AppFig.GetDebugInfo(); Debug.Log($"Rules loaded: {debug.rules.Count}"); Debug.Log($"Events logged: {debug.events.Count}"); Debug.Log($"User properties: {debug.userProperties.Count}"); Debug.Log($"Cached features: {debug.cachedResults.Count}"); ``` ## Using AppFigHelper (Optional) `AppFigHelper` is a MonoBehaviour that makes initialization easier with Inspector setup. ### Setup 1. Create an empty GameObject in your first scene 2. Add `AppFigHelper` component 3. Configure in Inspector: - Company ID: `your-company-id` - Tenant ID: `your-tenant-id` - Environment: `prod` or `dev` - API Key: `your-api-key` - Enable Debug Logs: ☑ (optional) ### Usage ```csharp // Access anywhere via singleton AppFigHelper.Instance.LogEvent("button_clicked"); string value = AppFigHelper.Instance.GetFeatureValue("max_lives"); if (AppFigHelper.Instance.IsFeatureEnabled("double_xp")) { ApplyDoubleXP(); } ``` ### No-Code Event Logging with Unity UI You can connect AppFigHelper methods directly to Unity UI components without writing any code! #### Button onClick Events **Setup:** 1. Select your Button in the scene 2. In the Inspector, find the **OnClick()** section 3. Click the **+** button to add a new event 4. Drag your AppFigHelper GameObject into the object field 5. Select **AppFigHelper** → **LogEvent(string)** 6. Enter your event name (e.g., "button_clicked") **Example:** ``` GameObject: PlayButton Component: Button OnClick(): - AppFigHelper.LogEvent("play_button_clicked") GameObject: SettingsButton Component: Button OnClick(): - AppFigHelper.LogEvent("settings_opened") ``` #### Tracking Multiple Interactions You can add multiple AppFigHelper calls to a single button: ``` GameObject: PurchaseButton Component: Button OnClick(): - AppFigHelper.LogEvent("purchase_initiated") - AppFigHelper.SetUserProperty("last_purchase_attempt", "now") - PurchaseManager.ProcessPurchase() // Your custom method ``` #### Dropdown onChange Events Track dropdown selections: ``` GameObject: DifficultyDropdown Component: Dropdown OnValueChanged(): - AppFigHelper.LogEvent("difficulty_changed") ``` #### Toggle onValueChanged Events Track toggle switches: ``` GameObject: SoundToggle Component: Toggle OnValueChanged(): - AppFigHelper.LogEvent("sound_toggled") ``` #### Slider onValueChanged Events Track slider adjustments: ``` GameObject: VolumeSlider Component: Slider OnValueChanged(): - AppFigHelper.LogEvent("volume_adjusted") ``` **Benefits:** - Zero code required for basic event logging - Quick prototyping and testing - Perfect for designers and non-programmers - Can be combined with custom scripts **Note:** For events with parameters, you'll still need to write a simple wrapper method. See [Logging Events](#logging-events) above. ## Visual Components (No Code!) ### AppFigApplier Apply feature values to GameObjects without writing code. **Use cases:** - Show/hide objects based on features - Update text with feature values - Set numeric values (light intensity, volume, speed) **Setup:** 1. Add `AppFigApplier` component to any GameObject 2. Set Feature Name (e.g., "show_bonus_ui") 3. Choose Apply Type: - **Enable/Disable**: Show/hide the GameObject - **Text Content**: Update Text/TextMeshPro component - **Numeric Value**: Set float value on component (volume, intensity, etc.) **Example:** ``` GameObject: BonusPanel Component: AppFigApplier - Feature Name: "bonus_panel" - Apply Type: Enable/Disable Rule: IF user completed 10+ levels THEN "bonus_panel" = "on" Result: BonusPanel appears after 10 level completions ``` ### AppFigABTester A/B test visual elements with unlimited variants. **Use cases:** - Test different button colors - Swap sprites/materials - Try different prefabs - Experiment with audio **Setup:** 1. Add `AppFigABTester` component to any GameObject 2. Set Feature Name (e.g., "button_color") 3. Choose Component Type (Sprite, Material, Color, Prefab, AudioClip) 4. Define variants with feature values **Example:** ``` GameObject: UpgradeButton Component: AppFigABTester - Feature Name: "button_color" - Component Type: Color (Image) - Variants: * Feature Value: "red" → Color: #FF0000 * Feature Value: "blue" → Color: #0000FF * Feature Value: "green" → Color: #00FF00 Rule: IF user from US THEN "button_color" = "red" Rule: IF user from EU THEN "button_color" = "blue" ``` ## Best Practices ### 1. Initialize Early Initialize in your first scene's `Start()` or `Awake()`: ```csharp void Awake() { AppFig.Init("company", "tenant", "prod", "api-key"); } ``` ### 2. Cache Feature Values Don't check the same feature repeatedly: ```csharp // ❌ Bad: Checks every frame void Update() { if (AppFig.IsFeatureEnabled("double_xp")) { // ... } } // ✅ Good: Check once, store result private bool hasDoubleXP; void Start() { hasDoubleXP = AppFig.IsFeatureEnabled("double_xp"); } void Update() { if (hasDoubleXP) { // ... } } ``` ### 3. Handle Null Values Always check for null: ```csharp string maxLives = AppFig.GetFeatureValue("max_lives"); if (maxLives != null) { int lives = int.Parse(maxLives); } else { int lives = 5; // Default fallback } ``` ### 4. Log Events Liberally The more events you log, the more powerful your targeting: ```csharp void CompleteLevel() { AppFig.LogEvent("level_complete", new Dictionary { { "level_number", currentLevel.ToString() }, { "time_seconds", timeElapsed.ToString() }, { "stars", starsEarned.ToString() } }); } ``` ### 5. Use Meaningful Event Parameters ```csharp // ✅ Good: Descriptive parameters AppFig.LogEvent("purchase_made", new Dictionary { { "item_id", "legendary_sword" }, { "price_usd", "9.99" }, { "payment_method", "credit_card" } }); // ❌ Bad: Vague parameters AppFig.LogEvent("purchase_made", new Dictionary { { "id", "123" }, { "amt", "999" } }); ``` ## Troubleshooting ### DLL not recognized by Unity **Problem:** Unity doesn't detect the DLL or shows import errors **Solutions:** 1. Verify `AppFigUnitySDK.dll` is in `Assets/Plugins/AppFig/` folder 2. Check the Inspector for the DLL - it should show "Plugin" as the type 3. Right-click in Project window and select "Refresh" to force Unity to re-import 4. If still not working, restart Unity Editor ### "The type or namespace name 'AppFig' could not be found" **Problem:** Scripts can't find AppFig classes **Solutions:** 1. Verify the DLL is properly imported (check Plugin Inspector) 2. Try reimporting: Right-click DLL → Reimport 3. Check Unity console for import errors or warnings 4. Ensure you're using Unity 2019.4 or higher (minimum supported version) ### "AppFig not initialized" **Problem:** Calling SDK methods before `Init()` **Solution:** ```csharp void Start() { AppFig.Init(...); // Must be first! AppFig.LogEvent("app_open"); // Now OK } ``` ### Feature always returns null **Problem:** No rules match for this feature **Solutions:** 1. Check feature name spelling (case-sensitive) 2. Verify rules are loaded: Check console for `[AppFig] ✅ Loaded X rule(s)` 3. Log relevant events/properties before checking feature 4. Enable debug logs to see rule evaluation ### Rules not updating **Problem:** Changes in dashboard not reflected in app **Solutions:** 1. Wait until auto-refresh interval passes 2. Call `AppFig.RefreshRules()` manually 3. Check console for `[AppFig] 🔄 Auto-refresh` messages 4. Verify internet connection ## Performance Tips ### Event History Management The SDK automatically manages event history to maintain optimal performance without manual intervention. ### Memory and CPU Usage AppFig has minimal memory and CPU overhead, making it suitable for production Unity applications across all platforms including mobile devices. The SDK is optimized for: - Low memory footprint - Fast feature checks with intelligent caching - Efficient rule evaluation While it's safe to check features frequently, we recommend caching feature values when possible to follow best practices. ## Next Steps - **[Rule Schema](https://appfig.com/docs/rule-schema)** - All rule options - **[Testing Guide](https://appfig.com/docs/testing)** - Test your features --- # Testing & Troubleshooting Source: https://appfig.com/docs/testing Complete guide to testing your feature flags and debugging issues. ## Testing Your Rules ### 1. Enable Debug Logging **Unity:** ```csharp // SDK automatically logs to Console // Look for lines starting with [AppFig] // Check what's loaded var debug = AppFig.GetDebugInfo(); Debug.Log($"Rules: {debug.rules.Count}"); Debug.Log($"Events: {debug.events.Count}"); ``` **React:** ```typescript await SmartConfig.init({ userId: 'test-user', tenant: 'my-app', source: 'cdn', debugMode: true // Enable verbose logging }); // Console will show: // [SmartConfig] 🔍 getConfig called for: welcome_message // [SmartConfig] 🔍 Rule matches: true // [SmartConfig] 🔍 Returning value: "Hello!" ``` ### 2. Test Event Logging Log events and verify they're tracked: **Unity:** ```csharp // Log event AppFig.LogEvent("test_event"); // Check it was recorded var events = AppFig.GetEventHistory(); Debug.Log($"Total events logged: {events.Count}"); // Verify specific event exists var testEvents = events.FindAll(e => e.name == "test_event"); Debug.Log($"Found {testEvents.Count} test_event occurrences"); ``` **React:** ```typescript // Log event SmartConfig.logEvent('test_event', { param: 'value' }); // Check it was recorded const events = SmartConfig.getEventHistory(); console.log('Total events:', events.length); console.log('Events:', events.map(e => e.name)); ``` ### 3. Test Properties Set properties and verify they're stored: **Unity:** ```csharp // Set properties AppFig.SetUserProperty("test_property", "test_value"); AppFig.SetDeviceProperty("test_device", "test_device_value"); // Check debug info var debug = AppFig.GetDebugInfo(); Debug.Log($"User properties: {debug.userProperties.Count}"); Debug.Log($"Device properties: {debug.deviceProperties.Count}"); ``` **React:** ```typescript // Set properties SmartConfig.setUserProperties({ test_property: 'test_value' }); // Check debug info const debug = SmartConfig.getDebugInfo(); console.log('User properties:', debug.userProperties); console.log('Device properties:', debug.deviceProperties); ``` ### 4. Test Rule Evaluation Create a simple test rule: ```json { "test_feature": [ { "conditions": { "events": { "mode": "simple", "operator": "AND", "items": [ { "key": "test_event", "count": { "operator": ">=", "value": 1 } } ] }, "user_properties": [], "device": [] }, "value": "success" } ] } ``` Test it step-by-step: ```csharp // Unity // 1. Before logging event string value1 = AppFig.GetFeatureValue("test_feature"); Debug.Log($"Before event: {value1}"); // null // 2. Log the event AppFig.LogEvent("test_event"); // 3. After logging event string value2 = AppFig.GetFeatureValue("test_feature"); Debug.Log($"After event: {value2}"); // "success" ``` ### 5. Test Time Windows ```json { "recent_activity": [ { "conditions": { "events": { "mode": "simple", "operator": "AND", "items": [ { "key": "app_open", "count": { "operator": ">=", "value": 1 }, "within_last_days": 7 } ] }, "user_properties": [], "device": [] }, "value": "active" } ] } ``` Test: ```csharp AppFig.LogEvent("app_open"); string status = AppFig.GetFeatureValue("recent_activity"); Debug.Log($"Status: {status}"); // "active" // To test old events, you can't easily fake timestamps ``` ## Common Issues ### Issue: Features Always Return Null **Symptoms:** - `GetFeatureValue()` always returns `null` - `IsFeatureEnabled()` always returns `false` **Diagnosis:** ```csharp // Check if rules are loaded var debug = AppFig.GetDebugInfo(); Debug.Log($"Rules loaded: {debug.rules.Count}"); if (debug.rules.Count == 0) { Debug.LogError("No rules loaded!"); } ``` **Common causes:** 1. **Rules not loaded** - Check console for `[AppFig] ✅ Loaded X rule(s)` message - Verify internet connection - Check API key is correct - Verify company/tenant IDs 2. **Feature name mismatch** ```csharp // Feature in JSON: "doubleXP" // Your code: "double_xp" ← Case mismatch! // Solution: Match exactly AppFig.GetFeatureValue("doubleXP"); ``` 4. **Conditions don't match** ```csharp // Rule requires 10 level_complete events // But you only logged 5 // Check event count var events = AppFig.GetEventHistory(); var levelEvents = events.FindAll(e => e.name == "level_complete"); Debug.Log($"Level events: {levelEvents.Count}"); ``` ### Issue: Rules Not Updating **Symptoms:** - Changed rules in dashboard - App still uses old rules **Solutions:** 1. **Wait for auto-refresh** - Default: 10 seconds - Check console for `[AppFig] 🔄 Auto-refresh` message 2. **Manual refresh** ```csharp AppFig.RefreshRules(); ``` 3. **Check auto-refresh is enabled** ```csharp // Enable if disabled AppFig.SetAutoRefresh(true); ``` 4. **Clear cache** ```csharp // Restart app to clear cached rules // Or call RefreshRules() ``` ### Issue: Initialization Failed **Symptoms:** - `[AppFig] Failed to load rules` in console - SDK methods throw errors **Solutions:** 1. **Check credentials** ```csharp // Verify all parameters are correct - use Firestore document IDs AppFig.Init( "acmegames", // Company ID from Firestore (not display name) "spaceshooter", // Tenant ID from Firestore (not display name) "prod", // or "dev" "your-api-key" // API key from dashboard ); ``` 2. **Check network** - Verify internet connection - Check firewall isn't blocking requests - Try from different network 3. **Check endpoint** - Console will show URL being fetched - Verify URL is accessible in browser ### Issue: Events Not Counted **Symptoms:** - Logged 10 events - Rule says count >= 10 - Feature still returns null **Diagnosis:** ```csharp // Check event history var events = AppFig.GetEventHistory(); Debug.Log($"Total events: {events.Count}"); // Check specific event var targetEvents = events.FindAll(e => e.name == "level_complete"); Debug.Log($"level_complete events: {targetEvents.Count}"); // Check if time window is restricting // Rules with within_last_days will filter out old events ``` **Solutions:** 1. **Event name mismatch** ```csharp // Rule: "level_complete" // Code: "levelComplete" ← Mismatch! // Fix: Match exactly AppFig.LogEvent("level_complete"); ``` 2. **Time window restriction** ```json { "key": "level_complete", "count": { "operator": ">=", "value": 10 }, "within_last_days": 7 // ← Only counts last 7 days! } ``` 3. **Parameter mismatch** ```json // Rule requires: { "key": "purchase", "param": { "amount": { "operator": ">", "value": 10 } } } ``` ```csharp // Your code doesn't include param AppFig.LogEvent("purchase"); // Won't match! // Fix: Include required parameter AppFig.LogEvent("purchase", new Dictionary { { "amount", "15" } }); ``` ### Issue: Properties Not Working **Symptoms:** - Set user/device property - Rule checks property - Feature still returns null **Diagnosis:** ```csharp // Check properties are set var debug = AppFig.GetDebugInfo(); Debug.Log($"User props: {string.Join(", ", debug.userProperties.Keys)}"); Debug.Log($"Device props: {string.Join(", ", debug.deviceProperties.Keys)}"); // Check specific property value if (debug.userProperties.TryGetValue("subscription_tier", out string value)) { Debug.Log($"subscription_tier = {value}"); } else { Debug.Log("subscription_tier not set!"); } ``` **Solutions:** 1. **Property not set** ```csharp // Make sure you set it before checking feature AppFig.SetUserProperty("subscription_tier", "premium"); // Then check feature if (AppFig.IsFeatureEnabled("premium_features")) { // ... } ``` 2. **Property name/value mismatch** ```json // Rule checks: { "key": "subscription_tier", "value": { "operator": "==", "value": "premium" } } ``` ```csharp // Your code: AppFig.SetUserProperty("subscriptionTier", "Premium"); // Wrong! Case matters for both key and value // Fix: AppFig.SetUserProperty("subscription_tier", "premium"); ``` 3. **Type mismatch** ```json // Rule expects string "true" { "key": "is_verified", "value": { "operator": "==", "value": "true" } } ``` ```csharp // Your code: AppFig.SetUserProperty("is_verified", "True"); // Capital T! // Fix: Match exactly AppFig.SetUserProperty("is_verified", "true"); ``` ## Testing Workflows ### Test Sequence: New User Flow ```csharp // 1. Reset session (simulate new user) AppFig.ResetSession(); // 2. Initialize AppFig.Init(...); // 3. Check welcome bonus (should be available) string bonus1 = AppFig.GetFeatureValue("welcome_bonus"); Debug.Log($"New user bonus: {bonus1}"); // "on" // 4. Make a purchase AppFig.LogEvent("purchase_made"); // 5. Check bonus again (should be gone if rule excludes purchasers) string bonus2 = AppFig.GetFeatureValue("welcome_bonus"); Debug.Log($"After purchase bonus: {bonus2}"); // null ``` ### Test Sequence: Engagement Flow ```csharp // 1. User opens app AppFig.LogEvent("app_open"); // 2. Completes levels for (int i = 0; i < 10; i++) { AppFig.LogEvent("level_complete"); } // 3. Check veteran bonus (should be available at 10 completions) string bonus = AppFig.GetFeatureValue("veteran_bonus"); Debug.Log($"Veteran bonus: {bonus}"); // "2x" ``` ### Test Sequence: Platform Check ```csharp // 1. Check auto-detected platform var debug = AppFig.GetDebugInfo(); string platform = debug.deviceProperties["platform"]; Debug.Log($"Platform: {platform}"); // 2. Check platform-specific feature string controls = AppFig.GetFeatureValue("mobile_controls"); Debug.Log($"Mobile controls: {controls}"); // Should be "on" for iOS/Android, null for desktop ``` ## Performance Testing ### Measure Feature Check Speed ```csharp var stopwatch = System.Diagnostics.Stopwatch.StartNew(); // First call (evaluates rules) string value1 = AppFig.GetFeatureValue("test_feature"); stopwatch.Stop(); Debug.Log($"First call: {stopwatch.ElapsedTicks} ticks"); stopwatch.Restart(); // Second call (cached) string value2 = AppFig.GetFeatureValue("test_feature"); stopwatch.Stop(); Debug.Log($"Second call: {stopwatch.ElapsedTicks} ticks"); // Expected results: // First call: ~1000-10000 ticks (~100 microseconds) // Second call: ~10-100 ticks (~0.5 microseconds) ``` ### Memory Usage ```csharp // Get memory before long memBefore = System.GC.GetTotalMemory(false); // Initialize SDK AppFig.Init(...); // Get memory after long memAfter = System.GC.GetTotalMemory(false); long memUsed = memAfter - memBefore; Debug.Log($"SDK memory usage: {memUsed / 1024} KB"); // Typical: 100-500 KB depending on rule complexity ``` ## Troubleshooting Checklist When features don't work as expected: - [ ] Rules loaded? Check console for load confirmation - [ ] Feature name matches exactly? (case-sensitive) - [ ] Events logged? Check event history - [ ] Properties set? Check debug info - [ ] Time windows correct? Recent enough events? - [ ] Parameters match? Check event params - [ ] Operators correct? `>=` not `>`, `==` not `=` - [ ] AND/OR logic correct? Check operators - [ ] NOT logic intended? Check `not` field - [ ] Multiple rules? First match wins - [ ] Cache cleared? Call RefreshRules() or restart ## Next Steps - **[Rule Schema](https://appfig.com/docs/rule-schema)** - Complete rule reference - **[Unity SDK](https://appfig.com/docs/unity-integration)** - Unity integration - **[React SDK](https://appfig.com/docs/react-web-guide)** - React integration --- # A/B Testing Reference Source: https://appfig.com/docs/ab-testing AppFig extends its rule engine with a lightweight, device-side multivariate testing (A/B testing) mode. It reuses the existing targeting system (events, sequences, user properties, device conditions) — there is no separate "experiment" concept to learn. ## Overview A/B testing in AppFig: - Assigns users to experiment variants **deterministically**, with zero network calls at evaluation time - **Persists the assignment on the device** so nobody flips to a different variant in the middle of a test - Works with or without a user id: a device without one is assigned by its device id - Reports each assignment to your analytics tool as a user property per experiment and a one-time assignment event This is not a separate rule type. It's a toggle on the **Return Value** section of an existing rule — all targeting logic (who the rule applies to) stays exactly the same whether the rule returns a static value or an A/B test. ## Data Model Each rule already has a `conditions` block (see [Rule Schema](https://appfig.com/docs/rule-schema)) that decides *who* the rule applies to. What changes is the return side — a rule returns **either**: ```json { "value": any } ``` **or** ```json { "ab_test": { "experiment_key": "string", "variants": [ { "name": "string", "weight": number, "value": any } ] } } ``` A rule never has both `value` and `ab_test` — the dashboard toggle decides which one a rule stores. **Fields:** - `experiment_key` (required) - Unique identifier for the experiment. Used in analytics and for deterministic assignment. - `variants` (required) - Array of possible outcomes for users who match this rule's conditions. - `name` (required) - Variant identifier, e.g. `"control"`, `"treatment"` - `weight` (required) - Relative weight for probabilistic assignment. Weights don't need to sum to 100 — they're normalized (e.g. `1`/`1` and `50`/`50` produce the same 50/50 split). - `value` (required) - What `getFeatureValue()` / `getConfig()` returns for a user assigned to this variant. Can be any JSON-serializable type, same as a normal rule's `value`. **Example: 50/50 button color test** ```json { "checkout_button_color": [ { "conditions": { "events": { "mode": "simple", "operator": "AND", "items": [] }, "user_properties": [], "user_properties_operator": "AND", "device": [], "device_operator": "AND" }, "ab_test": { "experiment_key": "checkout_button_color_test", "variants": [ { "name": "control", "weight": 1, "value": "blue" }, { "name": "treatment", "weight": 1, "value": "green" } ] } } ] } ``` **Example: Weighted rollout (10% treatment)** ```json { "new_onboarding_flow": [ { "conditions": { "events": { "mode": "simple", "operator": "AND", "items": [] }, "user_properties": [], "user_properties_operator": "AND", "device": [], "device_operator": "AND" }, "ab_test": { "experiment_key": "onboarding_v2_rollout", "variants": [ { "name": "control", "weight": 90, "value": "legacy" }, { "name": "treatment", "weight": 10, "value": "v2" } ] } } ] } ``` ## Dashboard: Toggle-Based A/B Test Mode In the dashboard rule builder, the condition builder (events, user properties, device) is untouched — A/B testing only changes the **Return Value** section: - **Toggle OFF** (default) - Single value input, same as any normal rule - **Toggle ON** (`Run as A/B Test`) - Replaces the value input with: - An experiment key field - A variants table (name, weight, value per row) This keeps targeting logic unified: you build your conditions once, and can flip a rule between "static value" and "A/B test" without redoing any targeting. ## Assignment Behavior *Describes SDK 2.1.0 and later. Differences from earlier versions are listed at the end of this section.* When a rule with an A/B test matches, the SDK decides the variant in this order: 1. **An assignment stored on the device wins.** Once a device has a variant for an `experiment_key`, it keeps it: across app restarts, after sign-in, after sign-out, and when you change the weights. 2. **Otherwise the user id is hashed, if one is set.** The same user id and `experiment_key` give the same variant on every device and every platform. 3. **Otherwise the device id is hashed.** The SDK creates this id on first launch and keeps it on the device. Apps without sign-in need nothing else. Assignment needs no network call, and it only happens when the rule's conditions match: a user who does not meet the conditions is not in the experiment and is not reported as part of it. What follows from this: - **A user id is optional.** Set one if a signed-in person should get the same variant on all their devices. To get that, set it before the SDK starts (before `init`); an experiment the device entered before the id was known keeps its device assignment. - **Changing weights affects only new assignments.** Devices already in the experiment keep their variant. - **Removing a variant** moves the devices that had it to a fresh assignment among the remaining variants. - **Changing the conditions** can take a user out of the experiment (the rule no longer matches them). If they match again later, they get the variant they had. - **Reinstalling the app** creates a new device id, so a device without a user id may land in a different variant. - **No experiment lifecycle on AppFig:** AppFig does not track start and end dates, statistical significance or winners. It assigns and remembers variants; you analyze the experiment in your analytics tool. **Typical workflow:** toggle a rule's Return Value to A/B Test → users start getting variants → you analyze results in your analytics tool → once you have a winner, toggle back to a static value and write the winning value directly. **Before SDK 2.1.0:** a device without a user id always received the first variant and was not counted in the experiment; assignments were kept for the session only; and calling `setUserId` assigned the device again. ## Analytics Integration The SDK reports assignments to the analytics tool you connect. It is the same whether the device was assigned by user id or by device id. **A user property per experiment** - **Name:** `af_` followed by the experiment key. Characters other than letters, digits and `_` become `_`, and the name is cut at 24 characters (the Google Analytics limit). `limit_test` becomes `af_limit_test`. - **Value:** the variant name. It is cleared when the experiment is no longer in your rules. Use it to segment any report or build an audience by variant. **An assignment event, once per device and experiment** Sent when the device enters the experiment, and not again on later app starts: | Tool | Event | Properties | |------|-------|------------| | Firebase / Google Analytics | `appfig_experiment` | `experiment`, `variant` | | Mixpanel | `$experiment_started` | `Experiment name`, `Variant name` | | Amplitude | `$exposure` | `flag_key`, `variant` | Use it as the starting point when you measure what users did after entering the experiment. In SDK 2.1.0 the Firebase / Google Analytics event was named `appfig_experiment_assigned` with the parameter `experiment_key`. From 2.2.0 it is `appfig_experiment` with `experiment`. **A feature event, for every feature the app reads (SDK 2.2.0 and later)** Experiments are not the only thing worth seeing in analytics. When your app reads a feature, the SDK sends `appfig_feature` with two parameters: | Parameter | Value | |-----------|-------| | `feature` | The feature's name | | `feature_value` | The value this device received, as text (cut at 100 characters) | It is sent once per device for each feature and value, and again only when the value this device gets changes. A feature the app never reads sends nothing. The event has the same name in every analytics tool. Use it to count how many users received a value after you changed it. In Google Analytics, register `feature` and `feature_value` (and `experiment`, `variant`) once as event-scoped custom dimensions; that covers every feature and experiment you add later. **The combined property** `appfig_experiments` is still set, as pipe-separated `experiment_key:variant_name` pairs: ``` "checkout_button_color_test:treatment|onboarding_v2_rollout:control" ``` Prefer the per-experiment properties: with several experiments running, the combined value exceeds the 36-character limit Google Analytics puts on user property values. ### Connecting a tool Firebase, Mixpanel and Amplitude have ready-made providers in the Unity, Android, iOS and React SDKs. Register one at startup: ```typescript AppFig.RegisterAnalyticsProvider(new FirebaseProvider(analytics)); ``` For any other tool, implement the provider interface. The assignment event method is optional: ```typescript class MyProvider implements IAnalyticsProvider { setUserProperty(key: string, value: string) { myAnalytics.setUserProperty(key, value); } trackExperimentAssigned(experimentKey: string, variantName: string) { myAnalytics.track('experiment_assigned', { experiment: experimentKey, variant: variantName }); } } AppFig.RegisterAnalyticsProvider(new MyProvider()); ``` In Flutter, pass two callbacks: ```dart AppFig.connectAnalytics( setUserProperty: (name, value) => FirebaseAnalytics.instance.setUserProperty(name: name, value: value.isEmpty ? null : value), logEvent: (name, parameters) => FirebaseAnalytics.instance.logEvent(name: name, parameters: parameters), ); ``` A provider can be registered before or after the SDK starts; assignments made earlier are delivered when it is registered. **BigQuery** needs no provider. With the Firebase provider connected and the Google Analytics BigQuery export turned on, the event and the properties arrive in your own BigQuery project. AppFig itself receives none of this data: assignments go from the device to your analytics tool. ## Next Steps - **[Experiments](https://appfig.com/docs/experiments)** - Test up to five values with one audience, and how results are measured - **[Rule Schema Reference](https://appfig.com/docs/rule-schema)** - Full targeting condition reference (applies identically to A/B test rules) - **[Rule Prioritization](https://appfig.com/docs/rule-prioritization)** - Control which RuleSet (static or A/B test) wins when several could match - **[Testing Guide](https://appfig.com/docs/testing)** - Test your rules --- # Experiments Source: https://appfig.com/docs/experiments An experiment is an A/B test with one audience and one set of variants, changing up to five values at once. Open it from **Menu → Experiments** in the dashboard. Every user in the experiment gets the same variant for every value in it, so a price and an ad frequency can be tested together. Under the hood an experiment is a set of ordinary [A/B test rules](https://appfig.com/docs/ab-testing), one per value, sharing one experiment key, one audience and the same variants. The Experiments screen keeps them in step. ## Building one | Part | What it is | |---|---| | **Name** | Shown in the dashboard and in results | | **Who is in it** | Events, user properties and device conditions, the same as any rule. Leave it empty for everyone. A user who stops matching leaves the experiment | | **Variants** | Up to 10, with whole-number shares that add up to 100%. The first variant is the control group. Names are 1 to 36 letters, digits, dashes or underscores (analytics tools cap property values at 36 characters) | | **Values** | Up to 5 features, each with a value per variant | | **What decides the winner** | More users who do an event, or more revenue per user (see below) | Start typing a key to pick a value the app already has; the screen shows its current value and its own rules. A key that doesn't exist yet becomes a new feature and counts in your plan. ### Leaving a cell empty An empty cell means *as it is*: users in that variant keep whatever the value's own rules give them today. The control group usually leaves every cell empty. When a value has its own rules (a different value for one country, say), a variant that keeps it "as it is" follows those rules, and the screen tells you which of them a variant with a typed value overrides. ### Where it sits Experiment rules go **above** a value's own rules, so they apply first to users in the audience; everyone else gets the value's own rules. In Features, an experiment's rules are locked and link back to Experiments, so audience, variants and values stay the same across every value in the experiment. When two experiments change the same value, a user who matches both audiences gets that value from the one higher in the list. Reorder them with the arrows; the screen warns about overlaps. ## Running it Saving writes to the **draft**. The experiment starts when you publish in Features, not when you save. Publish only after the app release that reads these values is live in the stores. If a rule changes in Features after the experiment was saved (an edit, or a value's own rule that an "as it is" cell follows), the screen offers to update the experiment's rules in the draft. **Stop** removes the experiment's rules from the draft, so every user goes back to each value's own rules after you publish. **Roll out** gives one variant's values to the experiment's audience as plain rules, also as a draft. ## How results are measured Results come from your own Google Analytics. The SDK gives each user a stable variant (user id when there is one, device id otherwise, remembered on the device) and sets a user property `af_` in your analytics tool. AppFig asks Google Analytics for each group since the experiment started. This needs Google Analytics connected and the property registered as a **user-scoped custom dimension**. AppFig registers it when it has the Editor role; otherwise the results screen says how. A new property takes a day or two to show data. ### More users who do an event The share of each group's users who sent the success event (a purchase, finishing onboarding, completing a level), compared with a two-proportion test. - Needs at least 100 users and 10 conversions per group - A winner is called only when the difference is unlikely to be chance (p < 0.05), with a 95% likely range - A variant that earns more than 5% less per user than control is never called the winner ### More revenue per user For prices, paywalls, trial lengths and ad frequency. Revenue is Google Analytics' total revenue: purchase events with a value and currency, and `ad_impression` events with a value (most ad networks send these), in your property's currency. Google Analytics gives totals, not each user's revenue, so the spread comes from days: revenue per user is read for each group on each day, and the day-by-day difference is tested against zero. - Needs at least 100 users per group and **at least 7 days with revenue in every group**, so it takes longer to call than conversion, which is the safe side when a few large spenders move the total - A winner is called only when the difference is unlikely to be chance, with a 95% likely range - The success event is optional here and only watched: a variant that earns more but clearly loses it is not called the winner - When no revenue reaches Google Analytics, the screen says so instead of comparing zeros ## Next Steps - **[A/B Testing Reference](https://appfig.com/docs/ab-testing)** - The rule format and what the SDKs send to analytics - **[Rule Prioritization](https://appfig.com/docs/rule-prioritization)** - Which rule wins when several match - **[Guided Setup](https://appfig.com/docs/guided-setup)** - From store link to first test --- # Rule Prioritization (RuleSet Ordering) Source: https://appfig.com/docs/rule-prioritization Lets you control which rule "wins" when multiple rules could apply to the same user, by setting an explicit evaluation order for the RuleSets inside a feature. ## How Evaluation Works - Each feature can have multiple **RuleSets** — rule blocks, each with their own conditions and return value (a static `value` or an [A/B test](https://appfig.com/docs/ab-testing)) - RuleSets are evaluated **top to bottom**, in the order shown in the dashboard UI - The **first RuleSet whose conditions match** the user wins — its value (or A/B test assignment) is returned and evaluation stops - If no RuleSet matches, no value is returned for that feature (`getFeatureValue()` / `getConfig()` returns `null`/`nil`) This is the same "first match wins" behavior already described in [Rule Schema](https://appfig.com/docs/rule-schema) and [Core Concepts](https://appfig.com/docs/concepts) — this page documents how you control the order. **Example:** ```json Feature: "veteran_bonus" RuleSet 1 (Priority #1): IF user completed 50+ levels → value = "3x" RuleSet 2 (Priority #2): IF user completed 10+ levels → value = "2x" (No match) → feature returns null ``` A user with 60 completed levels matches both RuleSets, but RuleSet 1 is evaluated first and wins — they get `"3x"`, not `"2x"`. ## Dashboard Controls - **Priority badge** - each RuleSet displays a numbered badge (`Priority #1`, `Priority #2`, ...) showing its position in the evaluation order - **Up / Down buttons** - reorder a RuleSet by moving it up or down relative to its siblings - The "up" button is disabled on the first RuleSet - The "down" button is disabled on the last RuleSet - **Info banner** - a short reminder above the RuleSet list: "RuleSets are evaluated top to bottom. The first matching rule's value is applied." Reordering takes effect the next time rules are published — no separate "activate ordering" step. ## Under the Hood - **No new database fields.** Priority is simply the array position of the RuleSet as stored — there's no explicit `priority` integer field to keep in sync. - **No backend/serializer changes.** The existing pipeline already preserves array order end-to-end (Firestore → JSON → CDN). - **No SDK changes.** SDKs already iterate RuleSets sequentially and return on the first match (see [Rule Schema](https://appfig.com/docs/rule-schema)), so reordering in the dashboard is immediately effective once published — no SDK update is required on any platform. ## Scope This ordering applies **within a feature** — it controls which of that feature's own RuleSets wins. It does **not** control the order in which different features are evaluated relative to each other; that's left entirely to your app's own logic (e.g. which `getFeatureValue()` calls you make and in what order). ## Next Steps - **[Rule Schema Reference](https://appfig.com/docs/rule-schema)** - Full condition and return-value reference - **[A/B Testing](https://appfig.com/docs/ab-testing)** - Use A/B test variants as a RuleSet's return value - **[Core Concepts](https://appfig.com/docs/concepts)** - "First Match Wins" principle --- # Rule Schema Reference Source: https://appfig.com/docs/rule-schema Complete reference for the AppFig rule schema (v2.0.0). ## Rule Structure A feature can have one or more rules. Each rule has: ```json { "conditions": { "events": { /* event conditions */ }, "user_properties": [ /* user property conditions */ ], "user_properties_operator": "AND" | "OR", "device": [ /* device conditions */ ], "device_operator": "AND" | "OR" }, "value": any // What to return if conditions match } ``` **All three condition types must pass for a rule to match** (AND logic between types). ## Event Conditions Events can be checked in two modes: **Simple** and **Sequence**. ### Simple Mode Check if events exist with certain criteria. ```json { "mode": "simple", "operator": "AND" | "OR", "items": [ { "key": "event_name", "count": { "operator": "==" | "!=" | ">" | "<" | ">=" | "<=", "value": number }, "within_last_days": number, "param": { "param_name": { "operator": "==" | "!=" | ">" | "<" | ">=" | "<=" | "in" | "not_in" | "contains", "value": any } }, "not": boolean } ] } ``` **Fields:** - `mode` - Must be `"simple"` - `operator` - How to combine items: `"AND"` (all must match) or `"OR"` (any can match) - `items` - Array of event conditions **Item fields:** - `key` (required) - Event name to match - `count` (optional) - How many times event must occur - `within_last_days` (optional) - Only count events in last N days - `param` (optional) - Match event parameters - `not` (optional) - Negate the condition (default: false) **Example: User completed 10+ levels AND made a purchase** ```json { "mode": "simple", "operator": "AND", "items": [ { "key": "level_complete", "count": { "operator": ">=", "value": 10 } }, { "key": "purchase_made", "count": { "operator": ">=", "value": 1 } } ] } ``` **Example: User opened app recently OR completed tutorial** ```json { "mode": "simple", "operator": "OR", "items": [ { "key": "app_open", "count": { "operator": ">=", "value": 1 }, "within_last_days": 7 }, { "key": "tutorial_complete", "count": { "operator": ">=", "value": 1 } } ] } ``` **Example: User has NOT made a purchase** ```json { "mode": "simple", "operator": "AND", "items": [ { "key": "purchase_made", "count": { "operator": ">=", "value": 1 }, "not": true } ] } ``` ### Sequence Mode Check if events occurred in a specific order. ```json { "mode": "sequence", "ordering": "direct" | "indirect", "steps": [ { "key": "event_name", "count": { "operator": "==" | "!=" | ">" | "<" | ">=" | "<=", "value": number }, "within_last_days": number, "param": { "param_name": { "operator": "==" | "!=" | ">" | "<" | ">=" | "<=" | "in" | "not_in" | "contains", "value": any } } } ] } ``` **Fields:** - `mode` - Must be `"sequence"` - `ordering` - Sequence type: - `"direct"` - Events must be consecutive (no other events between them) - `"indirect"` - Events must be in order but can have other events between - `steps` - Array of events in required order **Example: Onboarding flow (direct)** ```json { "mode": "sequence", "ordering": "direct", "steps": [ { "key": "tutorial_start" }, { "key": "tutorial_step_1" }, { "key": "tutorial_step_2" }, { "key": "tutorial_complete" } ] } ``` **Example: Engagement pattern (indirect)** ```json { "mode": "sequence", "ordering": "indirect", "steps": [ { "key": "app_open" }, { "key": "level_complete" }, { "key": "purchase_made" } ] } ``` ## User Property Conditions Check attributes of the user. ```json { "user_properties": [ { "key": "property_name", "value": { "operator": "==" | "!=" | ">" | "<" | ">=" | "<=" | "in" | "not_in" | "contains", "value": any }, "not": boolean } ], "user_properties_operator": "AND" | "OR" } ``` **Fields:** - `key` (required) - Property name - `value.operator` (required) - Comparison operator - `value.value` (required) - Value to compare against - `not` (optional) - Negate the condition (default: false) - `user_properties_operator` - How to combine multiple properties (default: `"AND"`) **Example: Premium users** ```json { "user_properties": [ { "key": "subscription_tier", "value": { "operator": "==", "value": "premium" } } ], "user_properties_operator": "AND" } ``` **Example: Premium OR trial users** ```json { "user_properties": [ { "key": "subscription_tier", "value": { "operator": "==", "value": "premium" } }, { "key": "trial_active", "value": { "operator": "==", "value": "true" } } ], "user_properties_operator": "OR" } ``` **Example: Account older than 30 days** ```json { "user_properties": [ { "key": "account_age_days", "value": { "operator": ">=", "value": 30 } } ] } ``` ## Device Conditions Check device/platform attributes (auto-detected by SDK). ```json { "device": [ { "key": "property_name", "value": { "operator": "==" | "!=" | ">" | "<" | ">=" | "<=" | "in" | "not_in" | "contains", "value": any }, "not": boolean } ], "device_operator": "AND" | "OR" } ``` **Auto-detected device properties:** | Property | Example Values | Description | |----------|---------------|-------------| | `platform` | `"iOS"`, `"Android"`, `"Windows"`, `"macOS"` | Operating system | | `os_version` | `"17.0"`, `"13"`, `"11.0"` | OS version string | | `language` | `"en-US"`, `"ja"`, `"es-ES"` | System language | | `country` | `"US"`, `"JP"`, `"GB"` | Country code (auto- detected from CDN) | | `timezone` | `"America/Los_Angeles"`, `"Asia/Tokyo"` | Timezone identifier | | `device_brand` | `"Apple"`, `"Samsung"`, `"Google"` | Device manufacturer | | `device_model` | `"iPhone 15"`, `"Galaxy S23"` | Device model | | `app_version` | `"1.2.3"` | App version (if set manually) | **Example: Mobile platforms only** ```json { "device": [ { "key": "platform", "value": { "operator": "in", "value": ["iOS", "Android"] } } ] } ``` **Example: US users only** ```json { "device": [ { "key": "country", "value": { "operator": "==", "value": "US" } } ] } ``` **Example: Exclude old OS versions** ```json { "device": [ { "key": "os_version", "value": { "operator": ">=", "value": "15.0" } } ] } ``` ## Operators ### Comparison Operators | Operator | Description | Example | |----------|-------------|---------| | `==` | Equals | `"premium" == "premium"` → true | | `!=` | Not equals | `"free" != "premium"` → true | | `>` | Greater than | `10 > 5` → true | | `<` | Less than | `5 < 10` → true | | `>=` | Greater or equal | `10 >= 10` → true | | `<=` | Less or equal | `5 <= 10` → true | **Type handling:** - Strings compared lexicographically - Numbers parsed and compared numerically - Booleans compared as strings ### Array Operators | Operator | Description | Example | |----------|-------------|---------| | `in` | Value in array | `"iOS" in ["iOS", "Android"]` → true | | `not_in` | Value not in array | `"Windows" not_in ["iOS", "Android"]` → true | ### String Operators | Operator | Description | Example | |----------|-------------|---------| | `contains` | String contains substring | `"hello world" contains "world"` → true | ## Value Types A value is one switch, number or text, stored as a string: **Boolean:** ```json { "value": "on" } // Checked with IsFeatureEnabled() { "value": "off" } ``` **String:** ```json { "value": "Welcome back!" } ``` **Number:** ```json { "value": "5" } // Stored as string, parse in your app { "value": "99.99" } ``` **One value per feature.** There are no object or list values. A Remote Config parameter that holds a whole JSON object is read field by field instead: each field becomes its own feature, and the JSON answers whenever AppFig has no value (see [Guided Setup](https://appfig.com/docs/guided-setup)). Fields that change together go in one [experiment](https://appfig.com/docs/experiments). ## Complete Example **Feature:** "premium_features" **Rules:** 1. Show "full" premium to paying users 2. Show "trial" premium to trial users who completed onboarding 3. Show nothing to everyone else (no matching rule) ```json { "premium_features": [ { "conditions": { "events": { "mode": "simple", "operator": "AND", "items": [] }, "user_properties": [ { "key": "subscription_tier", "value": { "operator": "==", "value": "premium" } } ], "user_properties_operator": "AND", "device": [], "device_operator": "AND" }, "value": "full" }, { "conditions": { "events": { "mode": "sequence", "ordering": "indirect", "steps": [ { "key": "onboarding_start" }, { "key": "onboarding_complete" } ] }, "user_properties": [ { "key": "trial_active", "value": { "operator": "==", "value": "true" } } ], "user_properties_operator": "AND", "device": [], "device_operator": "AND" }, "value": "trial" } ] } ``` ## Empty Conditions To match all users (always-on feature), use empty condition arrays: ```json { "conditions": { "events": { "mode": "simple", "operator": "AND", "items": [] }, "user_properties": [], "user_properties_operator": "AND", "device": [], "device_operator": "AND" }, "value": "on" } ``` This rule always matches and returns `"on"`. ## Next Steps - **[A/B Testing](https://appfig.com/docs/ab-testing)** - Use a rule's return value to run an experiment instead of a static value - **[Rule Prioritization](https://appfig.com/docs/rule-prioritization)** - Control which RuleSet wins when several could match - **[Testing Guide](https://appfig.com/docs/testing)** - Test your rules - **[Unity SDK](https://appfig.com/docs/unity-integration)** - Use rules in Unity - **[React SDK](https://appfig.com/docs/react-web-guide)** - Use rules in React