### Install and Run Example App
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/DEBUGGING.md
Commands to navigate to the example app directory, install dependencies, and run the app on iOS and Android simulators/devices.
```bash
cd example
npm install
# iOS
npx react-native run-ios
# Android
npx react-native run-android
```
--------------------------------
### Install iOS Native Dependencies
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/MIGRATION_GUIDE.md
Run `pod install` in the `ios` directory to install native dependencies for iOS.
```bash
cd ios && pod install && cd ..
```
--------------------------------
### Start Metro Server
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/example/README.md
Run this command in the root of your React Native project to start the Metro bundler.
```bash
npm start
```
--------------------------------
### Complete Migration Example: Before
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/MIGRATION_GUIDE.md
Shows the old API usage for initializing the SDK, identifying users, and tracking product view and purchase events.
```typescript
import Attentive, {
Mode,
type AttentiveConfiguration,
type ProductViewEvent,
type PurchaseEvent
} from '@attentive-mobile/attentive-react-native-sdk';
// Initialize
const config: AttentiveConfiguration = {
attentiveDomain: 'mystore',
mode: Mode.Production,
enableDebugger: false,
};
Attentive.initialize(config);
// Identify user
Attentive.identify({
email: 'user@example.com',
phone: '+15551234567',
});
// Track product view
const productView: ProductViewEvent = {
items: [{
productId: 'prod_123',
productVariantId: 'var_456',
price: {
price: '49.99',
currency: 'USD',
},
name: 'T-Shirt',
}],
deeplink: 'myapp://product/123',
};
Attentive.recordProductViewEvent(productView);
// Track purchase
const purchase: PurchaseEvent = {
items: [{
productId: 'prod_123',
productVariantId: 'var_456',
price: {
price: '49.99',
currency: 'USD',
},
}],
order: {
orderId: 'order_789',
},
};
Attentive.recordPurchaseEvent(purchase);
```
--------------------------------
### Navigate to Bonni Directory
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/Bonni/README.md
Changes the current directory to the Bonni example app's root folder within the repository.
```bash
cd Bonni
```
--------------------------------
### Usage Examples
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/GENERATION_REPORT.txt
A collection of realistic code examples demonstrating common use cases and integration patterns for the Attentive React Native SDK.
```APIDOC
## Usage Examples
This section provides over 45 realistic code examples showcasing various ways to integrate and utilize the Attentive React Native SDK. These examples are designed to be practical and cover common development scenarios.
### Example Scenarios:
- **Initialization**: Demonstrations of initializing the SDK in debug and production modes.
- **User Identification**: Workflows for identifying users within the application.
- **Event Recording**: Examples for tracking e-commerce events.
- **Push Notification Setup**: Comprehensive examples for setting up push notifications on both iOS and Android.
- **Error Handling**: Patterns for effectively handling errors within the SDK integration.
- **Complete Example App**: Reference to a full example application demonstrating end-to-end integration.
- **Integration Patterns**: Various methods for integrating the SDK into different parts of your application.
```
--------------------------------
### Install Android Native Dependencies
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/MIGRATION_GUIDE.md
Run `./gradlew clean` in the `android` directory to clean and install native dependencies for Android.
```bash
cd android && ./gradlew clean && cd ..
```
--------------------------------
### Install Attentive React Native SDK
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/quick-start.md
Install the SDK using npm. This is the first step before integrating the SDK into your React Native application.
```bash
npm install @attentive-mobile/attentive-react-native-sdk
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/Bonni/README.md
Installs all JavaScript dependencies for the project. Ensure Node.js version 18 or higher is used.
```bash
npm install
```
--------------------------------
### Initialize SDK
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/quick-start.md
Initialize the Attentive SDK once when your application starts. This is typically done in your root `App` component.
```APIDOC
## Initialize SDK
### Description
Initialize the Attentive SDK with your domain and mode.
### Method
`initialize(options: { attentiveDomain: string; mode: 'production' | 'staging'; })
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript
import { initialize } from '@attentive-mobile/attentive-react-native-sdk';
import { useEffect } from 'react';
export const App = () => {
useEffect(() => {
initialize({
attentiveDomain: 'myapp.attentivemobile.com',
mode: 'production'
});
}, []);
return ;
};
```
### Response
#### Success Response (200)
None
#### Response Example
None
```
--------------------------------
### Example Usage: Initialize, Record Event, and Debug
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/DEBUGGING.md
Demonstrates initializing the SDK with debugging enabled, recording a product view event which triggers the debug overlay, manually invoking the debug helper, and programmatically exporting debug logs.
```typescript
import {
initialize,
recordProductViewEvent,
invokeAttentiveDebugHelper,
exportDebugLogs,
} from '@attentive-mobile/attentive-react-native-sdk';
// Initialize with debugging
const config = {
attentiveDomain: 'games',
mode: 'debug',
enableDebugger: true,
};
initialize(config);
// Record an event - debug overlay will automatically appear
recordProductViewEvent({
items: [{
productId: 'test-product',
productVariantId: 'test-variant',
price: '29.99',
currency: 'USD',
}],
});
// Manually show debug info
invokeAttentiveDebugHelper();
// Export debug logs programmatically
const debugLogs = await exportDebugLogs();
console.log(debugLogs);
```
--------------------------------
### Handle Multiple Product Interaction Events
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/quick-start.md
This example demonstrates how to handle various product interactions by recording different events such as product views, add-to-cart, and custom remove-from-cart events. This allows for detailed tracking of user engagement with products.
```typescript
const handleProductInteraction = (product, action) => {
switch (action) {
case 'view':
recordProductViewEvent({ items: [product] });
break;
case 'add-to-cart':
recordAddToCartEvent({ items: [product] });
break;
case 'remove-from-cart':
recordCustomEvent({
type: 'remove_from_cart',
properties: { productId: product.productId }
});
break;
}
};
```
--------------------------------
### Complete Attentive SDK Integration Example
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/quick-start.md
This example demonstrates a full integration of the Attentive React Native SDK within a root component. It covers initialization, user identification, purchase event recording, and triggering creatives. Ensure you have the necessary imports and platform-specific configurations.
```typescript
import React, { useEffect, useState } from 'react';
import { View, Button, Alert, Platform } from 'react-native';
import {
initialize,
identify,
triggerCreative,
recordPurchaseEvent,
registerForPushNotifications,
getPushAuthorizationStatus
} from '@attentive-mobile/attentive-react-native-sdk';
export const App = () => {
const [userId, setUserId] = useState(null);
useEffect(() => {
// Initialize SDK
if (Platform.OS === 'ios') {
initialize({
attentiveDomain: 'myapp.attentivemobile.com',
mode: 'production'
});
}
// Request push permission
registerForPushNotifications();
}, []);
const handleUserLogin = (email: string, userId: string) => {
setUserId(userId);
identify({
email,
clientUserId: userId
});
};
const handlePurchase = () => {
recordPurchaseEvent({
items: [
{
productId: '123',
productVariantId: 'var-123',
price: '29.99',
currency: 'USD'
}
],
orderId: 'order-456'
});
// Show creative after purchase
triggerCreative();
};
return (
);
};
```
--------------------------------
### Initialize Attentive SDK (Debug Mode)
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/api-reference/sdk-initialization.md
Use this example to initialize the SDK in debug mode, enabling the debugger to show overlays when creatives trigger and events are recorded. This is useful for testing and development.
```typescript
useEffect(() => {
const config = {
attentiveDomain: 'myapp.attentivemobile.com',
mode: 'debug',
enableDebugger: true, // Show debug overlays
};
initialize(config);
}, []);
```
--------------------------------
### Initialize Attentive SDK (Android)
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/quick-start.md
Initialize the Attentive SDK within your `MainApplication.kt` file for Android. This setup requires providing the application context, domain, and operating mode.
```kotlin
import com.attentive.androidsdk.AttentiveConfig
import com.attentive.androidsdk.AttentiveSdk
class MainApplication : Application(), ReactApplication {
override fun onCreate() {
super.onCreate()
val config = AttentiveConfig.Builder()
.applicationContext(this)
.domain("myapp.attentivemobile.com")
.mode(AttentiveConfig.Mode.PRODUCTION)
.build()
AttentiveSdk.initialize(config)
}
}
```
--------------------------------
### Example Log Sequence for Testing
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/docs/PUSH_NOTIFICATIONS_INTEGRATION.md
Verify this sequence in the Xcode console when testing push notifications on a physical iOS device. This confirms successful token reception, authorization, registration, and event tracking.
```text
[Attentive] Device token received: ...
[Attentive] Authorization status:
[Attentive] Registration successful
[Attentive] Response status: 200
[Attentive] Regular open event triggered
```
--------------------------------
### Install iOS Pods
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/Bonni/README.md
Installs the necessary CocoaPods dependencies for the iOS project. Requires Ruby version 3.3 or higher, managed via rbenv.
```bash
npm run pods
```
--------------------------------
### Install Latest SDK Version
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/MIGRATION_GUIDE.md
Update the Attentive React Native SDK to the latest version using npm or yarn to ensure compatibility with the new architecture.
```bash
npm install @attentive-mobile/attentive-react-native-sdk@latest
# or
yarn add @attentive-mobile/attentive-react-native-sdk@latest
```
--------------------------------
### Fix iOS Build Failure: Missing Header
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/MIGRATION_GUIDE.md
Reinstall CocoaPods dependencies by removing the existing Pods and Podfile.lock, then running `pod install`.
```bash
cd ios
rm -rf Pods Podfile.lock
pod install
cd ..
npx react-native run-ios
```
--------------------------------
### Production Configuration with Fatigue Capping
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/configuration.md
Example of a production configuration where frequency capping is respected. This ensures creatives are shown according to the rules set in the Attentive system.
```typescript
const config = {
attentiveDomain: 'myapp.attentivemobile.com',
mode: 'production',
skipFatigueOnCreatives: false // Always respect frequency caps in production
};
```
--------------------------------
### Handle Initial Push Notification (React Native)
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/quick-start.md
Check if the app was launched due to a push notification and handle it accordingly. This is typically done when the app starts, using a `useEffect` hook.
```typescript
import { getInitialPushNotification, handlePushOpen, getPushAuthorizationStatus } from '@attentive-mobile/attentive-react-native-sdk';
useEffect(() => {
const checkPushNotification = async () => {
const notification = await getInitialPushNotification();
if (notification) {
const authStatus = await getPushAuthorizationStatus();
handlePushOpen(notification, authStatus);
}
};
checkPushNotification();
}, []);
```
--------------------------------
### Initialize SDK in Debug Mode with Dev Check
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/configuration.md
Initialize the SDK with debug mode enabled when the application is running in a development environment. This setup is useful for testing and debugging SDK behavior during development.
```typescript
import { initialize } from '@attentive-mobile/attentive-react-native-sdk';
import { __DEV__ } from 'react-native';
useEffect(() => {
const config = {
attentiveDomain: 'myapp.attentivemobile.com',
mode: __DEV__ ? 'debug' : 'production',
enableDebugger: __DEV__
};
initialize(config);
}, []);
```
--------------------------------
### Initialize and Identify User with New API
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/MIGRATION_GUIDE.md
Demonstrates initializing the SDK with configuration and identifying a user using the updated API.
```typescript
import { initialize, identify } from '@attentive-mobile/attentive-react-native-sdk';
describe('Attentive SDK', () => {
it('should initialize', () => {
initialize({
attentiveDomain: 'test',
mode: 'debug',
});
// assertions...
});
it('should identify user', () => {
identify({
email: 'test@example.com',
});
// assertions...
});
});
```
--------------------------------
### Initialize, Identify, and Track Events with New Attentive SDK API
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/MIGRATION_GUIDE.md
Use this snippet after migrating to the new API. It demonstrates initializing the SDK with configuration, identifying a user by email and phone, and recording product view and purchase events. Ensure all necessary types are imported.
```typescript
import {
initialize,
identify,
recordProductViewEvent,
recordPurchaseEvent,
type AttentiveSdkConfiguration,
type ProductView,
type Purchase
} from '@attentive-mobile/attentive-react-native-sdk';
// Initialize
const config: AttentiveSdkConfiguration = {
attentiveDomain: 'mystore',
mode: 'production',
enableDebugger: false,
};
initialize(config);
// Identify user
identify({
email: 'user@example.com',
phone: '+15551234567',
});
// Track product view
const productView: ProductView = {
items: [{
productId: 'prod_123',
productVariantId: 'var_456',
price: '49.99',
currency: 'USD',
name: 'T-Shirt',
}],
deeplink: 'myapp://product/123',
};
recordProductViewEvent(productView);
// Track purchase
const purchase: Purchase = {
items: [{
productId: 'prod_123',
productVariantId: 'var_456',
price: '49.99',
currency: 'USD',
}],
orderId: 'order_789',
};
recordPurchaseEvent(purchase);
```
--------------------------------
### getPushAuthorizationStatus()
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/api-reference/push-notifications.md
Gets the current push notification authorization status for the device. Returns a promise that resolves immediately and does not require user interaction.
```APIDOC
## getPushAuthorizationStatus()
### Description
Get the current push notification authorization status for the device.
### Method
```typescript
function getPushAuthorizationStatus(): Promise
```
### Parameters
None
### Return Type
`Promise` — Resolves to the current authorization status:
- `'authorized'` — User has granted permission
- `'denied'` — User has explicitly denied permission
- `'notDetermined'` — User has not been asked yet
- `'provisional'` — iOS only: provisional authorization (quiet notifications)
- `'ephemeral'` — iOS only: app clip notifications
### Behavior
- **iOS**: Queries `UNUserNotificationCenter` for current notification settings
- **Android**: Checks POST_NOTIFICATIONS permission (API 33+) or returns 'authorized' on older versions
- Returns a promise that resolves immediately (does not require user interaction)
### Example
```typescript
import { getPushAuthorizationStatus } from '@attentive-mobile/attentive-react-native-sdk';
const handleCheckPermissionStatus = async () => {
const status = await getPushAuthorizationStatus();
switch (status) {
case 'authorized':
console.log('Push notifications enabled');
break;
case 'denied':
console.log('User denied notifications');
break;
case 'notDetermined':
console.log('User has not been asked yet');
break;
}
};
```
```
--------------------------------
### Initialization & Lifecycle
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/README.md
Functions for initializing the SDK and managing its lifecycle.
```APIDOC
## initialize(config)
### Description
Initialize the SDK with configuration.
### Method
Not applicable (SDK function)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **config** (object) - Required - SDK configuration object.
### Request Example
```javascript
Attentive.initialize({ apiKey: 'YOUR_API_KEY', ...otherConfig });
```
### Response
None
## updateDomain(domain)
### Description
Change the domain at runtime.
### Method
Not applicable (SDK function)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **domain** (string) - Required - The new domain to set.
### Request Example
```javascript
Attentive.updateDomain('new.domain.com');
```
### Response
None
```
--------------------------------
### Testing Configuration Bypassing Fatigue Capping
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/configuration.md
Example of a testing configuration that bypasses frequency capping. Use this during development to repeatedly view creatives without hitting limits.
```typescript
const config = {
attentiveDomain: 'myapp.attentivemobile.com',
mode: 'debug',
skipFatigueOnCreatives: true // Bypass caps during testing
};
```
--------------------------------
### Testing Your Migration
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/MIGRATION_GUIDE.md
Instructions for verifying your SDK migration.
```APIDOC
## Type Checking
Ensure your TypeScript code compiles without errors.
```bash
npm run typecheck
# or
tsc --noEmit
```
## Manual Testing Checklist
- [ ] App initializes without errors
- [ ] User identification works
- [ ] Product view events are tracked
- [ ] Add to cart events are tracked
- [ ] Purchase events are tracked
- [ ] Custom events are tracked
- [ ] Creative triggers and dismisses correctly
- [ ] Debug helpers work (if enabled)
## Automated Testing
Update your tests to use the new API.
```typescript
import { initialize, identify } from '@attentive-mobile/attentive-react-native-sdk';
describe('Attentive SDK', () => {
it('should initialize', () => {
initialize({
attentiveDomain: 'test',
mode: 'debug',
});
// assertions...
});
it('should identify user', () => {
identify({
email: 'test@example.com',
});
// assertions...
});
});
```
```
--------------------------------
### Initialize SDK in Staging
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/configuration.md
Configuration for the staging environment, set to production mode with fatigue and debugger disabled.
```typescript
const config = {
attentiveDomain: 'myapp-staging.attentivemobile.com',
mode: 'production',
skipFatigueOnCreatives: false,
enableDebugger: false
};
```
--------------------------------
### Initialize SDK in Production
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/configuration.md
Configuration for the production environment, set to production mode with fatigue and debugger disabled.
```typescript
const config = {
attentiveDomain: 'myapp.attentivemobile.com',
mode: 'production',
skipFatigueOnCreatives: false,
enableDebugger: false
};
```
--------------------------------
### Get Initial Push Notification (TypeScript)
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/api-reference/complete-function-reference.md
Retrieves the push notification that launched the app from a killed state. This is platform-specific to Android; iOS uses `PushNotificationIOS`. The promise resolves to notification data or null.
```typescript
async function getInitialPushNotification(): Promise | null>
```
```typescript
const notification = await getInitialPushNotification();
if (notification) {
const authStatus = await getPushAuthorizationStatus();
handlePushOpen(notification, authStatus);
}
```
--------------------------------
### Initialize Main SDK Export
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/module-structure.md
Import all public API functions from the main SDK entry point. This includes functions for initialization, event tracking, user identification, creative management, debugging, push notifications, and marketing subscriptions.
```typescript
import {
initialize,
triggerCreative,
destroyCreative,
updateDomain,
identify,
clearUser,
recordAddToCartEvent,
recordProductViewEvent,
recordPurchaseEvent,
recordCustomEvent,
invokeAttentiveDebugHelper,
exportDebugLogs,
registerForPushNotifications,
getPushAuthorizationStatus,
registerDeviceToken,
registerDeviceTokenWithCallback,
handleRegularOpen,
handlePushOpened,
handleForegroundNotification,
handleForegroundPush,
handlePushOpen,
getInitialPushNotification,
optInMarketingSubscription,
optOutMarketingSubscription,
updateUser,
} from '@attentive-mobile/attentive-react-native-sdk';
```
--------------------------------
### Get Initial Push Notification (Android)
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/api-reference/push-notifications.md
Retrieve the push notification payload that launched the app from a killed state on Android. Call this once at app startup after initialization. The payload is cleared after retrieval and will only be delivered once.
```typescript
import { getInitialPushNotification, handlePushOpen, getPushAuthorizationStatus } from '@attentive-mobile/attentive-react-native-sdk';
// In your root App component useEffect
useEffect(() => {
const checkInitialNotification = async () => {
const initialNotification = await getInitialPushNotification();
if (initialNotification) {
const authStatus = await getPushAuthorizationStatus();
handlePushOpen(initialNotification as PushNotificationUserInfo, authStatus);
// Navigate to relevant screen based on notification
}
};
checkInitialNotification();
}, []);
```
--------------------------------
### initialize()
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/api-reference/sdk-initialization.md
Initializes the Attentive SDK with the provided configuration. This function must be called once per app session before any other SDK operations.
```APIDOC
## initialize()
### Description
Initialize the Attentive SDK with the provided configuration. This function is the primary entry point for setting up the SDK and must be called once per app session before any other SDK operations.
### Signature
```typescript
function initialize(configuration: AttentiveSdkConfiguration): void
```
### Parameters
#### configuration (`AttentiveSdkConfiguration`) - Required
Configuration object containing domain, mode, and optional debug settings.
### Configuration Object
```typescript
type AttentiveSdkConfiguration = {
attentiveDomain: string
mode: string // "production" or "debug"
skipFatigueOnCreatives?: boolean
enableDebugger?: boolean
}
```
### Configuration Parameters
- **attentiveDomain** (`string`) - Required - Your Attentive domain for the app (e.g., 'your-domain.attentivemobile.com')
- **mode** (`string`) - Required - Either `"production"` for normal operation or `"debug"` to show debug overlays without rendering the creative
- **skipFatigueOnCreatives** (`boolean`) - Optional - If `true`, bypass frequency capping rules for creatives
- **enableDebugger** (`boolean`) - Optional - If `true`, show debug overlays when creatives trigger and events are recorded
### Return Type
`void` — No return value. Errors are logged to the native layer.
### Behavior
- **iOS**: Initialization is performed from TypeScript (App component `useEffect`)
- **Android**: SDK must first be initialized from native code in `Application.onCreate()` before this function is called. See [Android Initialization](../android-setup.md) for details.
- The function is idempotent — calling it multiple times is safe
- All subsequent SDK operations (identify, triggerCreative, recordPurchaseEvent, etc.) depend on initialization being called
### Example
```typescript
import { initialize } from '@attentive-mobile/attentive-react-native-sdk';
// In your root App component
useEffect(() => {
const config = {
attentiveDomain: 'myapp.attentivemobile.com',
mode: 'production',
};
initialize(config);
}, []);
```
Debug mode example:
```typescript
useEffect(() => {
const config = {
attentiveDomain: 'myapp.attentivemobile.com',
mode: 'debug',
enableDebugger: true, // Show debug overlays
};
initialize(config);
}, []);
```
```
--------------------------------
### Initialization
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/MIGRATION_GUIDE.md
Initialize the Attentive SDK with the provided configuration object. Ensure you specify your Attentive domain and the desired mode (debug or production). Optional parameters like skipFatigueOnCreatives and enableDebugger can also be set.
```APIDOC
## Initialization
### Description
Initialize the Attentive SDK with the provided configuration object. Ensure you specify your Attentive domain and the desired mode (debug or production). Optional parameters like skipFatigueOnCreatives and enableDebugger can also be set.
### Method
initialize
### Parameters
#### Request Body
- **config** (AttentiveSdkConfiguration) - Required - Configuration object for the SDK.
- **attentiveDomain** (string) - Required - Your Attentive domain.
- **mode** ('debug' | 'production') - Required - SDK mode.
- **skipFatigueOnCreatives** (boolean) - Optional - Skip fatigue rules (default: false).
- **enableDebugger** (boolean) - Optional - Enable debug helpers (default: false).
### Request Example
```typescript
import { initialize, type AttentiveSdkConfiguration } from '@attentive-mobile/attentive-react-native-sdk';
const config: AttentiveSdkConfiguration = {
attentiveDomain: 'your-attentive-domain',
mode: 'debug',
skipFatigueOnCreatives: true,
enableDebugger: false,
};
initialize(config);
```
```
--------------------------------
### Run iOS Application
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/example/README.md
Execute this command in a new terminal from your project's root to launch the iOS application.
```bash
npm run ios
```
--------------------------------
### Initialize SDK in Development
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/configuration.md
Configure the SDK for development with debug mode, skipping fatigue, and enabling the debugger. Uses environment variables for the domain.
```typescript
import { initialize } from '@attentive-mobile/attentive-react-native-sdk';
import { __DEV__ } from 'react-native';
useEffect(() => {
const config = {
attentiveDomain: process.env.ATTENTIVE_DOMAIN || 'myapp-dev.attentivemobile.com',
mode: __DEV__ ? 'debug' : 'production',
skipFatigueOnCreatives: __DEV__, // Bypass caps in dev
enableDebugger: __DEV__
};
initialize(config);
}, []);
```
--------------------------------
### Get Push Notification Authorization Status
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/api-reference/push-notifications.md
Asynchronously retrieves the current push notification authorization status. This function is useful for determining whether to prompt the user for permission or to display relevant UI based on their existing settings. It resolves to one of 'authorized', 'denied', 'notDetermined', 'provisional', or 'ephemeral'.
```typescript
import { getPushAuthorizationStatus } from '@attentive-mobile/attentive-react-native-sdk';
const handleCheckPermissionStatus = async () => {
const status = await getPushAuthorizationStatus();
switch (status) {
case 'authorized':
console.log('Push notifications enabled');
break;
case 'denied':
console.log('User denied notifications');
break;
case 'notDetermined':
console.log('User has not been asked yet');
break;
}
};
```
--------------------------------
### Initialize SDK in Debug Mode
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/quick-start.md
Initialize the SDK with `mode: 'debug'` and `enableDebugger: true` to enable debug overlays during development.
```APIDOC
## Debug Mode
Enable during development to see debug overlays:
```typescript
initialize({
attentiveDomain: 'myapp.attentivemobile.com',
mode: 'debug',
enableDebugger: true
});
```
```
--------------------------------
### Opt In to Marketing
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/quick-start.md
Use `optInMarketingSubscription` to allow users to opt into marketing communications. It requires an object with `email` and `phone`.
```APIDOC
## Opt In to Marketing
```typescript
import { optInMarketingSubscription} from '@attentive-mobile/attentive-react-native-sdk';
const handleOptInMarketing = async () => {
try {
await optInMarketingSubscription({
email: 'user@example.com',
phone: '+15551234567'
});
} catch (error) {
console.error('Opt-in failed:', error);
}
};
```
```
--------------------------------
### Run Android Application
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/example/README.md
Execute this command in a new terminal from your project's root to launch the Android application.
```bash
npm run android
```
--------------------------------
### SDK Initialization
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/GENERATION_REPORT.txt
Initializes the Attentive React Native SDK with the provided configuration object. This is the first step required before using any other SDK functions.
```APIDOC
## initialize()
### Description
Initializes the Attentive React Native SDK. This function should be called once at the application's entry point with the necessary configuration.
### Method
`initialize(config: InitializationConfig)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **config** (InitializationConfig) - Required - An object containing the SDK configuration options.
* **apiKey** (string) - Required - Your Attentive API key.
* **domainId** (string) - Required - Your Attentive domain ID.
* **debugMode** (boolean) - Optional - Enables or disables debug mode. Defaults to false.
* **externalId** (string) - Optional - An external identifier for the user, if available at initialization.
### Request Example
```javascript
import { initialize } from '@attentive-mobile/attentive-react-native-sdk';
initialize({
apiKey: 'YOUR_API_KEY',
domainId: 'YOUR_DOMAIN_ID',
debugMode: true,
externalId: 'user123'
});
```
### Response
#### Success Response (void)
This function does not return a value upon successful initialization.
#### Response Example
N/A
```
--------------------------------
### Initialize Attentive SDK
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/MIGRATION_GUIDE.md
Initialize the Attentive SDK with the provided configuration object. Ensure `attentiveDomain` and `mode` are set.
```typescript
import { initialize, type AttentiveSdkConfiguration } from '@attentive-mobile/attentive-react-native-sdk';
const config: AttentiveSdkConfiguration = {
attentiveDomain: string; // Required: Your Attentive domain
mode: 'debug' | 'production'; // Required: SDK mode
skipFatigueOnCreatives?: boolean; // Optional: Skip fatigue rules (default: false)
enableDebugger?: boolean; // Optional: Enable debug helpers (default: false)
};
initialize(config);
```
--------------------------------
### Configuration Options
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/GENERATION_REPORT.txt
Details on the available configuration options for initializing and customizing the Attentive React Native SDK.
```APIDOC
## Configuration Options
This section outlines the various configuration options available for the Attentive React Native SDK. These options allow for customization of SDK behavior, such as initialization modes and feature toggles.
### Configuration Table:
- A table detailing all available configuration options, their types, default values (if any), and descriptions of their purpose and effect on the SDK's behavior.
```
--------------------------------
### Verify Entitlements for Production
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/docs/PUSH_NOTIFICATIONS_SETUP.md
Ensure the entitlements file contains the 'aps-environment' set to 'production' for TestFlight builds.
```xml
aps-environmentproduction
```
--------------------------------
### Correct SDK Import
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/module-structure.md
Import functions directly from the main entry point of the SDK for cleaner code. This is the recommended approach.
```typescript
// ✅ Correct
import { initialize, identify } from '@attentive-mobile/attentive-react-native-sdk';
```
--------------------------------
### Opt In to Marketing Subscriptions
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/quick-start.md
Use `optInMarketingSubscription` to allow users to opt into marketing communications. Handle potential errors during the opt-in process.
```typescript
import { optInMarketingSubscription} from '@attentive-mobile/attentive-react-native-sdk';
const handleOptInMarketing = async () => {
try {
await optInMarketingSubscription({
email: 'user@example.com',
phone: '+15551234567'
});
} catch (error) {
console.error('Opt-in failed:', error);
}
};
```
--------------------------------
### Initialize SDK on iOS
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/README.md
Call `initialize` from TypeScript as early as possible in your root `App` component's `useEffect`. This should be done once per app session before any other SDK operations.
```typescript
// Called once per app session, before any other SDK operations.
initialize(config);
```
--------------------------------
### Initialize Attentive SDK with Configuration
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/configuration.md
Configure and initialize the Attentive React Native SDK by passing an AttentiveSdkConfiguration object to the initialize() function. Ensure you replace 'YOUR_DOMAIN.attentivemobile.com' with your actual Attentive domain.
```typescript
import { initialize } from '@attentive-mobile/attentive-react-native-sdk';
const config = {
attentiveDomain: 'YOUR_DOMAIN.attentivemobile.com',
mode: 'production',
skipFatigueOnCreatives: false,
enableDebugger: false
};
initialize(config);
```
--------------------------------
### AttentiveSdkConfiguration
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/types.md
Configuration object passed to the `initialize()` function. It includes settings for the Attentive domain, operational mode, and optional flags for creative fatigue and debugger overlays.
```APIDOC
## AttentiveSdkConfiguration
### Description
Configuration object passed to the `initialize()` function.
### Type Definition
```typescript
type AttentiveSdkConfiguration = {
attentiveDomain: string
mode: string
skipFatigueOnCreatives?: boolean
enableDebugger?: boolean
}
```
### Fields
#### attentiveDomain
- **Type**: `string`
- **Required**: Yes
- **Description**: Your Attentive domain (e.g., 'myapp.attentivemobile.com')
#### mode
- **Type**: `string`
- **Required**: Yes
- **Description**: Either `"production"` for normal operation or `"debug"` for debug overlays
#### skipFatigueOnCreatives
- **Type**: `boolean`
- **Required**: No
- **Default**: `false`
- **Description**: If `true`, bypass frequency capping for creatives during testing
#### enableDebugger
- **Type**: `boolean`
- **Required**: No
- **Default**: `false`
- **Description**: If `true`, show debug overlays when events and creatives trigger
### Usage
**Used by:** `initialize()`
```
--------------------------------
### Troubleshoot 'No valid aps-environment entitlement found'
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/docs/PUSH_NOTIFICATIONS_SETUP.md
Ensure the 'Bonni.entitlements' file exists and is correctly linked in your Xcode Build Settings. Verify that 'aps-environment' is set to 'production' and perform a clean build.
```text
Issue: "No valid 'aps-environment' entitlement found"
Solution:
- Ensure `Bonni.entitlements` file exists and is linked in Build Settings
- Verify `aps-environment` is set to `production` (not `development`)
- Clean build folder and rebuild
```
--------------------------------
### Configure Entitlements for Development vs. Production
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/docs/PUSH_NOTIFICATIONS_SETUP.md
Use `aps-environment: development` for local development and testing. For TestFlight and App Store builds, use `aps-environment: production`. The current configuration is set to `production` for TestFlight compatibility.
```text
1. **Development vs Production**:
- For local development/testing: Use `aps-environment: development`
- For TestFlight/App Store: Use `aps-environment: production`
- The current configuration uses `production` for TestFlight compatibility
```
--------------------------------
### Initialize SDK on Android (Kotlin)
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/README.md
Initialize the SDK in `Application.onCreate()` in native Kotlin code. This ensures lifecycle observers are registered before the React Native bridge is ready and that initialization occurs on the main thread. Ensure `AttentiveConfig.Mode` is set appropriately for your environment.
```kotlin
import android.app.Application
import com.attentive.androidsdk.AttentiveConfig
import com.attentive.androidsdk.AttentiveSdk
import com.attentive.androidsdk.AttentiveLogLevel
class MainApplication : Application(), ReactApplication {
override fun onCreate() {
super.onCreate()
// ... your existing setup ...
initAttentiveSDK()
}
private fun initAttentiveSDK() {
val config = AttentiveConfig.Builder()
.applicationContext(this)
.domain("YOUR_ATTENTIVE_DOMAIN")
.mode(AttentiveConfig.Mode.PRODUCTION) // or Mode.DEBUG for testing
.notificationIconId(R.drawable.ic_stat_notification)
.skipFatigueOnCreatives(false)
.logLevel(AttentiveLogLevel.VERBOSE)
.build()
// Application.onCreate() is always called on the main thread by the Android system,
// so no thread-switching wrapper is needed here.
AttentiveSdk.initialize(config)
}
}
```
--------------------------------
### Complete AppDelegate Swift Implementation
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/docs/PUSH_NOTIFICATIONS_INTEGRATION.md
This complete AppDelegate.swift handles APNs token registration, failure, foreground notification display, and tap tracking. Ensure the SDK is initialized before any push or event calls.
```swift
import UIKit
import React
import React_RCTAppDelegate
import ReactAppDependencyProvider
import UserNotifications
import attentive_react_native_sdk
@main
class AppDelegate: RCTAppDelegate {
// Typed access to the SDK instance set by the React Native bridge
private var attentiveSdk: ATTNNativeSDK? {
return AttentiveSDKManager.shared.sdk as? ATTNNativeSDK
}
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
self.moduleName = "YourAppName"
self.dependencyProvider = RCTAppDependencyProvider()
self.initialProps = [: ]
UNUserNotificationCenter.current().delegate = self
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
override func sourceURL(for bridge: RCTBridge) -> URL? {
self.bundleURL()
}
override func bundleURL() -> URL? {
#if DEBUG
RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
#else
Bundle.main.url(forResource: "main", withExtension: "jsbundle")
#endif
}
// MARK: - Push Notification Handling
/// Registers the APNs device token with the Attentive backend and, once the
/// round-trip completes (success or failure), fires a regular-open event.
override func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
print("[Attentive] Device token received: \(tokenString.prefix(16))...")
UNUserNotificationCenter.current().getNotificationSettings { [weak self] settings in
guard let self = self else { return }
let authStatus = settings.authorizationStatus
print("[Attentive] Authorization status: \(authStatus.rawValue)")
self.attentiveSdk?.registerDeviceToken(
deviceToken,
authorizationStatus: authStatus,
callback: { data, url, response, error in
DispatchQueue.main.async {
if let error = error {
print("[Attentive] Registration failed: \(error.localizedDescription)")
} else {
print("[Attentive] Registration successful")
if let httpResponse = response as? HTTPURLResponse {
print("[Attentive] Response status: \(httpResponse.statusCode)")
}
}
// Always trigger regular open regardless of registration outcome
self.attentiveSdk?.handleRegularOpen(authorizationStatus: authStatus)
print("[Attentive] Regular open event triggered")
}
}
)
}
// Uncomment if you are also using RNCPushNotificationIOS:
// RNCPushNotificationIOS.didRegisterForRemoteNotifications(withDeviceToken: deviceToken)
}
/// Fires a regular-open event even when APNs registration fails so that
/// the app-open is still tracked regardless of notification permission state.
override func application(
_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error
) {
print("[Attentive] Failed to register for remote notifications: \(error.localizedDescription)")
UNUserNotificationCenter.current().getNotificationSettings { settings in
let sdk = AttentiveSDKManager.shared.sdk as? ATTNNativeSDK
DispatchQueue.main.async {
sdk?.handleRegularOpen(authorizationStatus: settings.authorizationStatus)
print("[Attentive] Regular open event triggered after registration failure")
}
}
}
```
--------------------------------
### Initialize SDK in Debug Mode
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/quick-start.md
Enable debug mode during development to see debug overlays. This requires specifying the `attentiveDomain`, setting the `mode` to 'debug', and `enableDebugger` to true.
```typescript
initialize({
attentiveDomain: 'myapp.attentivemobile.com',
mode: 'debug',
enableDebugger: true
});
```
--------------------------------
### Initialize SDK on iOS
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/configuration.md
Initialize the Attentive SDK from TypeScript for iOS applications. Ensure the domain and mode are set for production.
```typescript
import { initialize } from '@attentive-mobile/attentive-react-native-sdk';
import { useEffect } from 'react';
export const App = () => {
useEffect(() => {
initialize({
attentiveDomain: 'myapp.attentivemobile.com',
mode: 'production'
});
}, []);
return ;
};
```
--------------------------------
### Initialize and Identify User in Root Component
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/quick-start.md
Initialize the Attentive SDK and identify the user if their information is stored. This pattern is useful for ensuring the SDK is set up and the user is recognized on app startup.
```typescript
useEffect(() => {
// Initialize SDK
initialize({
attentiveDomain: 'myapp.attentivemobile.com',
mode: 'production'
});
// Get stored user info
const userEmail = await AsyncStorage.getItem('userEmail');
const userId = await AsyncStorage.getItem('userId');
// Identify if we have user info
if (userEmail || userId) {
identify({
email: userEmail,
clientUserId: userId
});
}
}, []);
```
--------------------------------
### Run Android App
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/Bonni/README.md
Commands to run the Android application. Choose the script that best fits your development workflow, from standard development to fresh SDK builds.
```bash
npm run android
```
```bash
npm run android-fresh
```
```bash
npm run android-pure
```
--------------------------------
### Initialize SDK with Debugger Enabled
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/configuration.md
Initialize the SDK with `enableDebugger` set to `true` for development builds. This automatically enables debug features when `__DEV__` is true.
```typescript
import { initialize } from '@attentive-mobile/attentive-react-native-sdk';
import { __DEV__ } from 'react-native';
// Automatic based on development vs. production
useEffect(() => {
const config = {
attentiveDomain: 'myapp.attentivemobile.com',
mode: __DEV__ ? 'debug' : 'production',
enableDebugger: __DEV__
};
initialize(config);
}, []);
```
--------------------------------
### Initialize Attentive SDK in Production Mode
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/api-reference/debugging.md
Initialize the Attentive SDK for normal operation in production mode. In this mode, creatives render normally, debug overlays are not shown, and logging is minimal for performance.
```typescript
const config = {
attentiveDomain: 'your-domain.attentivemobile.com',
mode: 'production' // Normal operation
// enableDebugger not needed in production
};
initialize(config);
```
--------------------------------
### Opt-in Marketing Subscription (TypeScript)
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/api-reference/complete-function-reference.md
Opt a user into email and/or SMS marketing. Requires at least one of `email` or `phone` in the `MarketingSubscriptionParams`. The function returns a promise that resolves on success or rejects with an error.
```typescript
function optInMarketingSubscription(
params: MarketingSubscriptionParams
): Promise
```
```typescript
{
email?: string,
phone?: string
}
```
```typescript
try {
await optInMarketingSubscription({
email: 'user@example.com',
phone: '+15551234567'
});
} catch (error) {
console.error('Opt-in failed:', error);
}
```
--------------------------------
### Platform-Specific Behavior
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/GENERATION_REPORT.txt
Documentation highlighting differences in SDK behavior and integration steps between iOS and Android platforms.
```APIDOC
## Platform-Specific Behavior
This section addresses platform-specific aspects of the Attentive React Native SDK, ensuring developers are aware of any differences in implementation or behavior between iOS and Android.
### Key Areas Covered:
- **Initialization**: Differences in initialization procedures (e.g., TypeScript vs. native code).
- **Push Notifications**: Specifics regarding APNs (iOS) and FCM (Android).
- **Function Behavior**: Any documented variations in how certain functions operate on each platform.
- **AppDelegate Integration**: Examples specific to iOS AppDelegate setup.
```
--------------------------------
### Initialize Attentive SDK
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/api-reference/complete-function-reference.md
Initialize the Attentive SDK with your domain and mode. This must be called once per app session before any other SDK operations. Ensure Android initialization is handled natively.
```typescript
initialize({
attentiveDomain: 'myapp.attentivemobile.com',
mode: 'production'
});
```
--------------------------------
### Initialize Attentive SDK (Production Mode)
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/api-reference/sdk-initialization.md
Call this function once in your root App component's useEffect hook to initialize the SDK in production mode. Ensure the `attentiveDomain` is correctly set.
```typescript
import { initialize } from '@attentive-mobile/attentive-react-native-sdk';
// In your root App component
useEffect(() => {
const config = {
attentiveDomain: 'myapp.attentivemobile.com',
mode: 'production',
};
initialize(config);
}, []);
```
--------------------------------
### Record Product View Event
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/_autodocs/quick-start.md
Record a product view event to track which products users are interested in. Include product details like ID, price, and name.
```typescript
import { recordProductViewEvent } from '@attentive-mobile/attentive-react-native-sdk';
recordProductViewEvent({
items: [
{
productId: '12345',
productVariantId: 'var-67890',
price: '29.99',
currency: 'USD',
name: 'Widget Pro'
}
]
});
```
--------------------------------
### Rebuild App for iOS
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/MIGRATION_GUIDE.md
Rebuild the application for iOS using `npx react-native run-ios`.
```bash
# iOS
npx react-native run-ios
```
--------------------------------
### Create AttentiveConfig in Production Mode
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/README.md
Configure the Attentive SDK for production use by providing your attentive domain and setting the mode to 'production'.
```typescript
const config: AttentiveSdkConfiguration = {
attentiveDomain: 'YOUR_ATTENTIVE_DOMAIN',
mode: 'production',
}
```
--------------------------------
### Rebuild App for Android
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/MIGRATION_GUIDE.md
Rebuild the application for Android using `npx react-native run-android`.
```bash
# Android
npx react-native run-android
```
--------------------------------
### Load the Creative
Source: https://github.com/attentive-mobile/attentive-react-native-sdk/blob/main/README.md
Triggers the Attentive Creative to display as a pop-up over the current application interface.
```APIDOC
## triggerCreative
### Description
Initiates the display of the Attentive Creative, which appears as a modal or pop-up overlaying the application.
### Method Signature
`triggerCreative()`
### Request Example
```typescript
triggerCreative();
```
```