### SDK Setup
Source: https://context7_llms
Instructions for initializing the Phase Analytics SDK in your application, covering both SwiftUI and UIKit.
```APIDOC
## SDK Setup
### SwiftUI Setup
Wrap your app with the `Phase` view to initialize the SDK:
```swift
import SwiftUI
import PhaseAnalytics
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
Phase(apiKey: "phase_xxx") {
ContentView()
}
}
}
}
```
### UIKit Setup
Initialize the SDK in your AppDelegate:
```swift
import UIKit
import PhaseAnalytics
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
Task {
try await PhaseSDK.shared.initialize(apiKey: "phase_xxx")
}
return true
}
}
```
**Note:** The SDK initialization is asynchronous. You must call `identify()` before tracking events.
```
--------------------------------
### Install iOS Dependencies with CocoaPods
Source: https://phase.sh/docs/get-started/react-native
Installs necessary dependencies for iOS projects using CocoaPods. Navigate to the 'ios' directory in your project and run the 'pod install' command.
```bash
cd ios && pod install
```
--------------------------------
### PhaseProvider Setup
Source: https://context7_llms
Wrap your application with the PhaseProvider component to initialize the SDK. This component requires an API key and can optionally be configured with navigation and other settings.
```APIDOC
## Setup
Wrap your app with the `PhaseProvider` component to initialize the SDK:
### Request Example
```tsx
import { PhaseProvider } from 'phase-analytics/react-native';
import { NavigationContainer } from '@react-navigation/native';
export default function App() {
return (
);
}
```
The `PhaseProvider` only initializes the SDK. You must call `Phase.identify()` before tracking events.
```
--------------------------------
### Setup PhaseProvider in Root Layout (React)
Source: https://phase.sh/docs/get-started/expo
Wraps the application's root layout with the PhaseProvider component to initialize the Phase Analytics SDK. This component requires the API key and can accept optional configuration props.
```typescript
import { PhaseProvider } from 'phase-analytics/expo';
export default function RootLayout() {
return (
{/* Your app content */}
);
}
```
--------------------------------
### Install Phase Analytics SDK (npm, bun, yarn, pnpm)
Source: https://phase.sh/docs/get-started/expo
Installs the Phase Analytics SDK for Expo React Native using various package managers. Ensure you have Node.js and a compatible package manager installed.
```bash
npm install phase-analytics
```
```bash
bun add phase-analytics
```
```bash
yarn add phase-analytics
```
```bash
pnpm add phase-analytics
```
--------------------------------
### Initialize Phase Analytics with PhaseProvider
Source: https://phase.sh/docs/get-started/react-native
Wraps your React Native application with the `PhaseProvider` component to initialize the Phase Analytics SDK. This setup should be done at the root of your application, typically in `App.tsx`.
```typescript
import { PhaseProvider } from 'phase-analytics/react-native';
import { NavigationContainer } from '@react-navigation/native';
export default function App() {
return (
{/* Your app content */}
);
}
```
--------------------------------
### Identify User with Phase SDK
Source: https://phase.sh/docs/get-started/swift
Example of identifying a user with the Phase SDK, including initial identification without PII and subsequent identification with custom properties after obtaining user consent. Properties must be primitives.
```swift
import SwiftUI
import PhaseAnalytics
struct ContentView: View {
var body: some View {
Text("Hello, World!")
.onAppear {
Task {
// Initialize analytics - no PII collected by default
await PhaseSDK.shared.identify()
}
}
}
}
// After user login and consent
// await PhaseSDK.shared.identify([ "user_id": "123", "plan": "premium", "beta_tester": true ])
// ⚠️ If adding PII, get consent first
// let hasConsent = await customGetUserConsent()
// if hasConsent {
// await PhaseSDK.shared.identify([ "email": "user@example.com", "name": "John Doe" ])
// }
```
--------------------------------
### Install Required Peer Dependencies for React Native
Source: https://phase.sh/docs/get-started/react-native
Installs essential peer dependencies required for Phase Analytics to function correctly in a React Native environment. These include packages for storage, device info, localization, network status, and navigation.
```npm
npm install @react-native-async-storage/async-storage react-native-device-info react-native-localize @react-native-community/netinfo @react-navigation/native
```
```bun
bun add @react-native-async-storage/async-storage react-native-device-info react-native-localize @react-native-community/netinfo @react-navigation/native
```
```yarn
yarn add @react-native-async-storage/async-storage react-native-device-info react-native-localize @react-native-community/netinfo @react-navigation/native
```
```pnpm
pnpm add @react-native-async-storage/async-storage react-native-device-info react-native-localize @react-native-community/netinfo @react-navigation/native
```
--------------------------------
### Identify User
Source: https://context7_llms
Call `Phase.identify()` to register the device and start a session. This method can optionally include custom user properties. Ensure user consent if PII is included.
```APIDOC
## Identify User
**Required:** Call `Phase.identify()` before using any other methods. This registers the device and starts a session.
### Request Example
```tsx
import { Phase } from 'phase-analytics/react-native';
import { useEffect } from 'react';
export default function App() {
useEffect(() => {
// Initialize analytics - no PII collected by default
Phase.identify();
}, []);
return ;
}
```
**Privacy by default:**
* No personal data is collected without explicit properties
* Device ID is auto-generated and stored locally
* Only technical metadata is collected (OS version, platform, locale)
**Adding custom properties:**
You can optionally attach user properties. **Important:** If you add PII (personally identifiable information), ensure you have proper user consent:
### Request Example
```tsx
// After user login and consent
await Phase.identify({
user_id: '123',
plan: 'premium',
beta_tester: true
});
// ⚠️ If adding PII, get consent first
const hasConsent = await customGetUserConsent();
if (hasConsent) {
await Phase.identify({
email: 'user@example.com',
name: 'John Doe'
});
}
```
Properties must be primitives: `string`, `number`, `boolean`, or `null`.
```
--------------------------------
### Install Required Peer Dependencies for Expo
Source: https://phase.sh/docs/get-started/expo
Installs essential Expo packages required for Phase Analytics to function, including file system, device information, localization, and routing. Uses various package managers with 'expo install'.
```bash
npx expo install expo-file-system expo-device expo-localization expo-router
```
```bash
bunx expo install expo-file-system expo-device expo-localization expo-router
```
```bash
yarn dlx expo install expo-file-system expo-device expo-localization expo-router
```
```bash
pnpm dlx expo install expo-file-system expo-device expo-localization expo-router
```
--------------------------------
### Automatic Screen Tracking Setup in React Native
Source: https://phase.sh/docs/get-started/react-native
Enables automatic tracking of screen views in React Native applications by setting `trackNavigation` to `true` and providing a `navigationRef`. This feature requires `react-navigation` and is integrated within the `PhaseProvider`.
```typescript
import { PhaseProvider } from 'phase-analytics/react-native';
import { NavigationContainer, useNavigationContainerRef } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
const Stack = createNativeStackNavigator();
export default function App() {
const navigationRef = useNavigationContainerRef();
return (
{/* Your screens here */}
);
}
```
--------------------------------
### Initialize Phase Analytics in Expo App
Source: https://context7_llms
This snippet shows how to initialize the Phase Analytics SDK within an Expo application using the `useEffect` hook to ensure it's called after the component mounts. It requires the 'phase-analytics/expo' package and is fundamental for starting analytics collection.
```tsx
import { Phase } from 'phase-analytics/expo';
import { useEffect } from 'react';
export default function App() {
useEffect(() => {
// Initialize analytics - no PII collected by default
Phase.identify();
}, []);
return ;
}
```
--------------------------------
### Identify User with Phase Analytics (React)
Source: https://phase.sh/docs/get-started/expo
Initializes user identification and starts a session using Phase.identify(). This is a required step before tracking events. It supports adding custom, non-PII properties by default and can include PII with user consent.
```typescript
import { Phase } from 'phase-analytics/expo';
import { useEffect } from 'react';
export default function App() {
useEffect(() => {
// Initialize analytics - no PII collected by default
Phase.identify();
}, []);
return (
// Your app content
);
}
// Example with custom properties (ensure consent for PII):
// await Phase.identify({
// user_id: '123',
// plan: 'premium',
// beta_tester: true
// });
// const hasConsent = await customGetUserConsent();
// if (hasConsent) {
// await Phase.identify({
// email: 'user@example.com',
// name: 'John Doe'
// });
// }
```
--------------------------------
### Identify User with Phase Analytics SDK
Source: https://context7_llms
Call `Phase.identify()` to register the device and start a session before tracking any events. This function can be called with an empty object for default privacy settings or with custom properties like `user_id`, `plan`, and `beta_tester`. When adding Personally Identifiable Information (PII) such as `email` or `name`, ensure user consent is obtained first. Properties must be primitive types (string, number, boolean, null).
```tsx
import { Phase } from 'phase-analytics/react-native';
import { useEffect } from 'react';
export default function App() {
useEffect(() => {
// Initialize analytics - no PII collected by default
Phase.identify();
}, []);
return ;
}
```
```tsx
// After user login and consent
await Phase.identify({
user_id: '123',
plan: 'premium',
beta_tester: true
});
// ⚠️ If adding PII, get consent first
const hasConsent = await customGetUserConsent();
if (hasConsent) {
await Phase.identify({
email: 'user@example.com',
name: 'John Doe'
});
}
```
--------------------------------
### Initialize Phase SDK in SwiftUI App
Source: https://phase.sh/docs/get-started/swift
Demonstrates how to wrap your SwiftUI application with the 'Phase' view to initialize the SDK. This method requires your API key and a closure for your app's content.
```swift
import SwiftUI
import PhaseAnalytics
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
Phase(apiKey: "phase_xxx") {
ContentView()
}
}
}
}
```
--------------------------------
### Initialize Phase SDK in UIKit AppDelegate
Source: https://phase.sh/docs/get-started/swift
Shows how to initialize the Phase SDK asynchronously in the AppDelegate for UIKit applications. Ensure to call 'identify()' after initialization. Requires an API key.
```swift
import UIKit
import PhaseAnalytics
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
Task {
try await PhaseSDK.shared.initialize(apiKey: "phase_xxx")
}
return true
}
}
```
--------------------------------
### SDK Configuration
Source: https://context7_llms
Details on the parameters available for configuring the Phase SDK during initialization.
```APIDOC
## SDK Configuration
The `Phase` view and `initialize()` method accept the following parameters:
- **apiKey** (String) - Required - Your Phase API key (starts with `phase_`)
- **baseURL** (String) - Optional - Custom API endpoint for self-hosted deployments. Defaults to `"https://api.phase.sh"`.
- **logLevel** (LogLevel) - Optional - Console logging level for debugging. Defaults to `.none`.
- **deviceInfo** (Bool) - Optional - Collect device metadata (model, OS version, platform). Defaults to `true`.
- **userLocale** (Bool) - Optional - Collect user locale and timezone information. Defaults to `true`.
```
--------------------------------
### Initialize Phase Analytics SDK with PhaseProvider in React Native Expo
Source: https://context7_llms
Sets up the Phase Analytics SDK by wrapping the application's root layout with the PhaseProvider component. This requires providing your unique API key obtained from the Phase Dashboard. This step initializes the SDK for use across the application.
```tsx
import { PhaseProvider } from 'phase-analytics/expo';
export default function RootLayout() {
return (
);
}
```
--------------------------------
### Identify User with Phase Analytics
Source: https://phase.sh/docs/get-started/react-native
Identifies a user and starts a session using `Phase.identify()`. This method should be called before any other Phase Analytics methods. It can optionally include custom user properties.
```typescript
import { Phase } from 'phase-analytics/react-native';
import { useEffect } from 'react';
export default function App() {
useEffect(() => {
// Initialize analytics - no PII collected by default
Phase.identify();
}, []);
return (
// Your app content
);
}
```
```typescript
// After user login and consent
await Phase.identify({
user_id: '123',
plan: 'premium',
beta_tester: true
});
// ⚠️ If adding PII, get consent first
const hasConsent = await customGetUserConsent();
if (hasConsent) {
await Phase.identify({
email: 'user@example.com',
name: 'John Doe'
});
}
```
--------------------------------
### PhaseProvider Configuration
Source: https://context7_llms
Configure the PhaseProvider component with essential props like apiKey, trackNavigation, baseUrl, logLevel, deviceInfo, and userLocale.
```APIDOC
## PhaseProvider Component Configuration
### Description
Configure the root component of your application with the `PhaseProvider` to initialize the analytics SDK. This component accepts various props to customize its behavior and data collection.
### Props
#### `apiKey`
- **Type**: `string`
- **Required**: Yes
- **Description**: Your unique Phase API key, which typically starts with `phase_`.
#### `trackNavigation`
- **Type**: `boolean`
- **Required**: No
- **Default**: `false`
- **Description**: If set to `true`, the SDK will automatically track screen views when using Expo Router.
#### `baseUrl`
- **Type**: `string`
- **Required**: No
- **Default**: `"https://api.phase.sh"`
- **Description**: Use this for self-hosted deployments to specify a custom API endpoint.
#### `logLevel`
- **Type**: `"info" | "warn" | "error" | "none"`
- **Required**: No
- **Default**: `"none"`
- **Description**: Sets the console logging level for debugging purposes.
#### `deviceInfo`
- **Type**: `boolean`
- **Required**: No
- **Default**: `true`
- **Description**: Enable or disable the collection of device metadata such as model, OS version, and platform.
#### `userLocale`
- **Type**: `boolean`
- **Required**: No
- **Default**: `true`
- **Description**: Enable or disable the collection of user locale and timezone information.
### Example Usage
```tsx
import { PhaseProvider } from 'phase-analytics/expo';
import { Stack } from 'expo-router';
export default function RootLayout() {
return (
);
}
```
```
--------------------------------
### Initialize PhaseProvider in React Native App
Source: https://context7_llms
Wrap your application with the `PhaseProvider` component to initialize the Phase Analytics SDK. This component requires an `apiKey` and can optionally accept configuration for navigation, custom API endpoints, logging, and device/user information collection. It must be placed within a `NavigationContainer` if `trackNavigation` is enabled.
```tsx
import { PhaseProvider } from 'phase-analytics/react-native';
import { NavigationContainer } from '@react-navigation/native';
export default function App() {
return (
);
}
```
--------------------------------
### PhaseProvider Configuration
Source: https://context7_llms
The PhaseProvider component accepts several props for configuration, including API key, navigation integration, and data collection settings.
```APIDOC
## Configuration
The `PhaseProvider` component accepts the following props:
| Prop Name | Description | Type | Required | Default |
|----------------|------------------------------------------------------|--------------------|----------|---------|
| `apiKey` | Your Phase API key (starts with `phase_`) | `string` | Yes | - |
| `navigationRef`| Navigation container ref for automatic screen tracking | `NavigationContainerRef` | No | - |
| `trackNavigation` | Automatically track screen views with React Navigation | `boolean` | No | `false` |
| `baseUrl` | Custom API endpoint for self-hosted deployments | `string` | No | `"https://api.phase.sh"` |
| `logLevel` | Console logging level for debugging | `"info" | "warn" | "error" | "none"` | No | `"none"` |
| `deviceInfo` | Collect device metadata (model, OS version, platform) | `boolean` | No | `true` |
| `userLocale` | Collect user locale and timezone information | `boolean` | No | `true` |
```
--------------------------------
### LLM Usage Billing with Polar Ingestion
Source: https://polar.sh/
This example demonstrates how to implement usage-based billing for LLM services using Polar's ingestion strategies. It captures customer LLM usage, including prompt and completion tokens, and supports Vercel AI SDK. The code requires the `@polar-sh/ingestion` package and an `accessToken`. It outputs the generated text from the LLM.
```typescript
import { Ingestion } from "@polar-sh/ingestion";
import { LLMStrategy } from "@polar-sh/ingestion/strategies/LLM";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";
const llmIngestion = Ingestion({
accessToken: 'xxx'
})
.strategy(new LLMStrategy(openai("gpt-4o")))
.ingest("openai-usage");
export async function POST(req: Request) {
const { prompt }: { prompt: string } = await req.json();
const model = llmIngestion.client({
externalCustomerId: "",
});
const { text } = await generateText({
model,
system: "You are a helpful assistant.",
prompt,
});
return Response.json({ text });
}
```
--------------------------------
### Enable Automatic Screen Tracking in Expo Router
Source: https://context7_llms
Shows how to enable automatic screen tracking in an Expo application by wrapping the root navigation component with `PhaseProvider` and setting the `trackNavigation` prop to `true`. This feature leverages Expo Router to automatically track screen views based on route changes, simplifying analytics setup for navigation.
```tsx
import { PhaseProvider } from 'phase-analytics/expo';
import { Stack } from 'expo-router';
export default function RootLayout() {
return (
);
}
```
--------------------------------
### Track Events with Phase SDK
Source: https://phase.sh/docs/get-started/swift
Demonstrates tracking custom events, both with and without parameters, using the Phase SDK. 'identify()' must be called prior to tracking events. Event names have specific formatting rules and parameters must be primitives.
```swift
// Event without parameters
track("app_opened")
// Event with parameters
track("purchase_completed", [ "amount": 99.99, "currency": "USD", "product_id": "premium_plan" ])
// Using instance method
PhaseSDK.shared.track("button_clicked", params: ["button_id": "submit"])
```
--------------------------------
### Track Screen View in Swift
Source: https://phase.sh/docs/get-started/swift
Tracks a user's screen view using the PhaseSDK. The `trackScreen` method takes the screen name and optional parameters. No external dependencies are required beyond the PhaseSDK.
```swift
PhaseSDK.shared.trackScreen("/settings", params: nil)
```
--------------------------------
### React Native UI Components for Documentation
Source: https://context7_llms
This snippet showcases the import statements for UI components from 'fumadocs-ui' used in generating documentation for React Native applications. These components include steps, type tables, tabs, and code blocks, facilitating structured and interactive documentation.
```javascript
import { Step, Steps } from 'fumadocs-ui/components/steps';
import { TypeTable } from 'fumadocs-ui/components/type-table';
import { Tab, Tabs, TabsList, TabsTrigger, TabsContent } from 'fumadocs-ui/components/tabs';
import { CodeBlock, Pre } from 'fumadocs-ui/components/codeblock';
```
--------------------------------
### Add Swift Package for Phase Analytics
Source: https://context7_llms
Integrate the Phase Analytics SDK into your iOS or macOS project using Swift Package Manager. This involves adding the repository URL to Xcode's package dependencies or specifying it in your `Package.swift` file. Requires iOS 15.0+ or macOS 12.0+, and Swift 6.0+.
```swift
dependencies: [
.package(url: "https://github.com/Phase-Analytics/Phase", from: "0.0.28")
]
```
--------------------------------
### How It Works - Performance
Source: https://phase.sh/docs/get-started/react-native
Phase Analytics optimizes performance through asynchronous event batching, network state monitoring, and retry mechanisms with exponential backoff.
```APIDOC
## How It Works - Performance
### Description
- Offline events are batched and sent asynchronously.
- Network state is monitored via `@react-native-community/netinfo`.
- Failed requests retry with exponential backoff.
- Maximum batch size: 1000 events.
### Method
Automatic
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
#### Response Example
N/A
```
--------------------------------
### Add Swift Package to Project
Source: https://phase.sh/docs/get-started/swift
Instructions for adding the Phase Analytics Swift Package to your Xcode project or Package.swift file. Requires Xcode, iOS 15.0+/macOS 12.0+, and Swift 6.0+.
```swift
dependencies: [
.package(url: "https://github.com/Phase-Analytics/Phase", from: "0.0.28")
]
```
--------------------------------
### Type Reference
Source: https://phase.sh/docs/get-started/react-native
Reference for custom user/device attributes and event parameters.
```APIDOC
## Type Reference
### DeviceProperties
Custom user/device attributes passed to `Phase.identify()`.
- **Prop Type**: `[key: string]?`string | number | boolean | null
### EventParams
Event parameters passed to `Phase.track()`.
- **Prop Type**: `[key: string]?`string | number | boolean | null
```
--------------------------------
### Track Events with Phase SDK
Source: https://context7_llms
Tracks custom events with optional parameters. The `identify()` method must be called prior to tracking any events. Event names have specific formatting rules, and parameters must be primitive data types.
```swift
// Event without parameters
track("app_opened")
// Event with parameters
track("purchase_completed", [
"amount": 99.99,
"currency": "USD",
"product_id": "premium_plan"
])
// Using instance method
PhaseSDK.shared.track("button_clicked", params: ["button_id": "submit"])
```
--------------------------------
### How It Works - Offline Support
Source: https://phase.sh/docs/get-started/react-native
Phase Analytics automatically queues events locally using `@react-native-async-storage/async-storage` when the device is offline and syncs them when the connection is restored.
```APIDOC
## How It Works - Offline Support
### Description
Events are queued locally using `@react-native-async-storage/async-storage` when offline. The queue automatically syncs when connection is restored.
### Method
Automatic
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
#### Response Example
N/A
```