mirror of
https://github.com/BillyOutlast/posthog.com.git
synced 2026-02-04 03:11:21 +01:00
Split ios sdk pages (#13379)
* split ios sdk pages * Update contents/docs/libraries/ios/index.mdx Co-authored-by: Ian Vanagas <34755028+ivanagas@users.noreply.github.com> * Apply suggestions from code review Co-authored-by: Ian Vanagas <34755028+ivanagas@users.noreply.github.com> * review comments * Autocapture, config table * Apply suggestion from @ivanagas Co-authored-by: Ian Vanagas <34755028+ivanagas@users.noreply.github.com> * Apply suggestions from code review Co-authored-by: Ian Vanagas <34755028+ivanagas@users.noreply.github.com> * Unique import names * Address comments --------- Co-authored-by: Ian Vanagas <34755028+ivanagas@users.noreply.github.com> Co-authored-by: Eli Kinsey <eli@ekinsey.dev>
This commit is contained in:
committed by
GitHub
parent
2cb2742a6f
commit
4fec074149
@@ -14,7 +14,7 @@ pod "PostHog", "~> 3.0"
|
||||
|
||||
Add PostHog as a dependency in your Xcode project "Package Dependencies" and select the project target for your app, as appropriate.
|
||||
|
||||
For a Swift Package Manager based project, add PostHog as a dependency in your "Package.swift" file's Package dependencies section:
|
||||
For a Swift Package Manager based project, add PostHog as a dependency in your `Package.swift` file's Package dependencies section:
|
||||
|
||||
```swift file=Package.swift
|
||||
dependencies: [
|
||||
@@ -32,6 +32,10 @@ and then as a dependency for the Package target utilizing PostHog:
|
||||
|
||||
### Configuration
|
||||
|
||||
Configuration is done through the `PostHogConfig` object. Here's a basic configuration example to get you started.
|
||||
|
||||
You can find more advanced configuration options in the [configuration page](/docs/libraries/ios/configuration).
|
||||
|
||||
<Tab.Group tabs={['App Delegate/UIKit', 'SwiftUI Lifecycle']}>
|
||||
<Tab.List>
|
||||
<Tab>UIKit</Tab>
|
||||
@@ -45,4 +49,4 @@ and then as a dependency for the Package target utilizing PostHog:
|
||||
{IOSSwiftUI}
|
||||
</Tab.Panel>
|
||||
</Tab.Panels>
|
||||
</Tab.Group>
|
||||
</Tab.Group>
|
||||
@@ -11,15 +11,9 @@ PostHog autocapture automatically tracks the following events for you:
|
||||
|
||||
> 🚧 **Note:** `$autocapture` is currently supported only in UIKit.
|
||||
|
||||
### Autocapture configuration
|
||||
|
||||
You can enable or disable autocapture through the `PostHogConfig` object.
|
||||
|
||||
<AutocaptureConfig />
|
||||
|
||||
### Capturing screen views
|
||||
|
||||
With [`configuration.captureScreenViews`](/docs/libraries/ios#all-configuration-options) set as `true`, PostHog will try to record all screen changes automatically.
|
||||
With [`configuration.captureScreenViews`](/docs/libraries/ios/configuration#all-configuration-options) set as `true`, PostHog will try to record all screen changes automatically.
|
||||
|
||||
If you want to manually send a new screen capture event, use the `screen` function.
|
||||
|
||||
@@ -103,4 +97,23 @@ To locate and filter interactions with specific elements in PostHog reports, you
|
||||
- Text (`text value` in this example)
|
||||
- CSS Selector (the generated `id` attribute in this example)
|
||||
|
||||
In the examples above, we can filter for the specific text field using the CSS Selector `#usernameTextField`
|
||||
In the examples above, we can filter for the specific text field using the CSS Selector `#usernameTextField`
|
||||
|
||||
### Interaction autocapture
|
||||
|
||||
Interaction autocapture records when users interact with UI elements in your app. This includes:
|
||||
|
||||
- User interactions like `touch`, `swipe`, `pan`, `pinch`, `rotation`, `long_press`, `scroll`
|
||||
- Control types `value_changed`, `submit`, `toggle`, `primary_action`, `menu_action`, `change`
|
||||
|
||||
Interaction autocapture is **not enabled by default**. You can enable it by setting `captureElementInteractions` to `true` in the config.
|
||||
|
||||
```swift
|
||||
let config = PostHogConfig(apiKey: <ph_project_api_key>, host: <ph_client_api_host>)
|
||||
config.captureElementInteractions = true // Disabled by default
|
||||
PostHogSDK.shared.setup(config)
|
||||
```
|
||||
|
||||
### Autocapture configuration
|
||||
|
||||
You can enable or disable autocapture through the `PostHogConfig` object. Find more details about autocapture configuration in the [configuration page](/docs/libraries/ios/configuration#autocapture-configuration).
|
||||
241
contents/docs/libraries/ios/configuration.mdx
Normal file
241
contents/docs/libraries/ios/configuration.mdx
Normal file
@@ -0,0 +1,241 @@
|
||||
---
|
||||
title: iOS SDK configuration
|
||||
sidebarTitle: iOS
|
||||
sidebar: Docs
|
||||
showTitle: true
|
||||
github: 'https://github.com/PostHog/posthog-ios'
|
||||
icon: >-
|
||||
https://res.cloudinary.com/dmukukwp6/image/upload/posthog.com/contents/images/docs/integrate/ios.svg
|
||||
features:
|
||||
eventCapture: true
|
||||
userIdentification: true
|
||||
autoCapture: true
|
||||
sessionRecording: true
|
||||
featureFlags: true
|
||||
groupAnalytics: true
|
||||
surveys: true
|
||||
llmAnalytics: false
|
||||
---
|
||||
|
||||
import iosAutocaptureConfiguration from './_snippets/autocapture.mdx'
|
||||
|
||||
## Autocapture configuration
|
||||
|
||||
You can enable or disable autocapture through the `PostHogConfig` object.
|
||||
|
||||
<iosAutocaptureConfiguration />
|
||||
|
||||
## Flush configuration
|
||||
|
||||
The iOS SDK uses an internal queue to make calls fast and non-blocking. It also batches requests and flushes asynchronously, making it perfect to use in any part of your mobile app.
|
||||
|
||||
You can set the number of events in the configuration that should queue before flushing.
|
||||
|
||||
Setting this to `1` will send events immediately and will use more battery. This is set to `20` by default.
|
||||
|
||||
```swift
|
||||
configuration.flushAt = 1
|
||||
```
|
||||
|
||||
You can also manually flush the queue:
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.capture("logged_out")
|
||||
PostHogSDK.shared.flush()
|
||||
```
|
||||
|
||||
## Amending, dropping or sampling events
|
||||
|
||||
Since version 3.28.0, you can provide a `BeforeSendBlock` function when initializing the SDK to amend, drop or sample events before they are sent to PostHog.
|
||||
|
||||
> **⚠️ Note:** This replaces the deprecated `propertiesSanitizer` option and provides more flexibility in modifying events. You can achieve the same functionality as `propertiesSanitizer` by using a `BeforeSendBlock` that mutates the event's properties in place.
|
||||
|
||||
> **🚨 Warning:** Amending and sampling events is advanced functionality that requires careful implementation. Core PostHog features may require 100% of unmodified events to function properly. We recommend only modifying or sampling your own custom events if possible, and preserving all PostHog internal events in their original form.
|
||||
|
||||
### Redacting information in events
|
||||
|
||||
`BeforeSendBlock` gives you one place to edit or redact information before it is sent to PostHog. For example:
|
||||
|
||||
<details>
|
||||
<summary>Redact URLs in event properties</summary>
|
||||
|
||||
```swift
|
||||
let config = PostHogConfig(apiKey: "<ph_project_api_key>", host: "<ph_api_client_host>")
|
||||
|
||||
config.setBeforeSend { event in
|
||||
// Redact URLs
|
||||
if let url = event.properties["url"] as? String {
|
||||
event.properties["url"] = url.map { _ in "*" }.joined()
|
||||
}
|
||||
return event
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Redact sensitive information from event properties</summary>
|
||||
|
||||
```swift
|
||||
let config = PostHogConfig(apiKey: "<ph_project_api_key>", host: "<ph_api_client_host>")
|
||||
|
||||
config.setBeforeSend { event in
|
||||
// Redact sensitive information
|
||||
if let email = event.properties["email"] as? String {
|
||||
event.properties["email"] = email.map { _ in "*" }.joined()
|
||||
}
|
||||
|
||||
return event
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Drop events by event name</summary>
|
||||
|
||||
```swift
|
||||
let config = PostHogConfig(apiKey: "<ph_project_api_key>", host: "<ph_api_client_host>")
|
||||
|
||||
config.setBeforeSend { event in
|
||||
// Drop all events named "Stale Event"
|
||||
if event.event == "Stale Event" {
|
||||
return nil
|
||||
}
|
||||
return event
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
### Sampling events
|
||||
|
||||
Sampling lets you choose to send only a percentage of events to PostHog. It is a good way to control your costs without having to completely turn off features of the SDK.
|
||||
|
||||
<details>
|
||||
<summary>Sample events by event name</summary>
|
||||
|
||||
```swift
|
||||
let config = PostHogConfig(apiKey: "<ph_project_api_key>", host: "<ph_api_client_host>")
|
||||
|
||||
config.setBeforeSend { event in
|
||||
// Sample 10% of Sampled Event events
|
||||
if event.event == "Sampled Event" {
|
||||
if Double.random(in: 0...1) < 0.1 {
|
||||
event.properties["$sample_type"] = ["sampleByEvent"]
|
||||
event.properties["$sample_threshold"] = 0.1
|
||||
event.properties["$sampled_events"] = ["Sampled Event"]
|
||||
return event
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return event
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
### Chaining multiple BeforeSendBlocks
|
||||
|
||||
You can provide an array of `BeforeSendBlock` functions to be called one after the other:
|
||||
|
||||
```swift
|
||||
let config = PostHogConfig(apiKey: "<ph_project_api_key>", host: "<ph_api_client_host>")
|
||||
|
||||
config.setBeforeSend(
|
||||
// First block: Drop all events named "Stale Event"
|
||||
{ event in
|
||||
if event.event == "Stale Event" {
|
||||
return nil
|
||||
}
|
||||
return event
|
||||
},
|
||||
// Second block: Redact sensitive information
|
||||
{ event in
|
||||
if let email = event.properties["email"] as? String {
|
||||
event.properties["email"] = email.map { _ in "*" }.joined()
|
||||
}
|
||||
return event
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
**Note:** When chaining beforeSend blocks, order is important. The first block is executed first and the mutated event is passed along to the second block, and so on. If at any point in the chain the event is dropped, any subsequent blocks will not be executed.
|
||||
|
||||
## Setting up app groups
|
||||
|
||||
1. **Configure App Groups**: Set up an [App Group](https://developer.apple.com/documentation/xcode/configuring-app-groups) in Xcode for your main app and extension targets
|
||||
2. **Configure PostHog**: Use the same App Group identifier in all targets:
|
||||
|
||||
```swift
|
||||
let config = PostHogConfig(apiKey: "<ph_project_api_key>", host: "<ph_api_client_host>")
|
||||
config.appGroupIdentifier = "group.com.yourcompany.yourapp"
|
||||
PostHogSDK.shared.setup(config)
|
||||
```
|
||||
|
||||
## Method swizzling
|
||||
|
||||
Method swizzling is a technique that enables the SDK to intercept and modify method calls at runtime to provide advanced features like screen view tracking, element interactions, session replay, surveys, and more.
|
||||
|
||||
Method swizzling is enabled by default, but can be disabled by setting the relevant config option to `false` in the `PostHogConfig` object:
|
||||
|
||||
| Feature | Description | Config option |
|
||||
| ------------------------------ | ------------------------------------------------------------------------------------- | -------------------------------- |
|
||||
| Screen view tracking | Automatically captures when view controllers are presented | `config.captureScreenViews` |
|
||||
| Element interactions | Automatically tracks user interactions with UI elements | `config.captureElementInteractions` |
|
||||
| Session replay | Records user sessions | `config.sessionReplay` |
|
||||
| Surveys | Displays surveys at appropriate times | `config.surveys` |
|
||||
| Advanced metrics tracking | Provides more precise session ID calculation and rotation by detecting user activity and idleness | — |
|
||||
|
||||
|
||||
### Disabling all method swizzling
|
||||
|
||||
Since version 3.34.0, you can opt out of all swizzling using the `enableSwizzling` configuration option. When you disable swizzling, the SDK disables the features listed above.
|
||||
|
||||
```swift
|
||||
let config = PostHogConfig(apiKey: "<ph_project_api_key>", host: "<ph_api_client_host>")
|
||||
config.enableSwizzling = false
|
||||
PostHogSDK.shared.setup(config)
|
||||
```
|
||||
|
||||
> **Note:** When method swizzling is disabled, features that depend on it will not work even if they are individually enabled in the config. For example, if you set `config.sessionReplay = true` and `config.enableSwizzling = false`, session replay will **not** be enabled.
|
||||
|
||||
### Session metrics management
|
||||
|
||||
Method swizzling is particularly important for accurate [session metrics tracking](/tutorials/session-metrics). With swizzling enabled, the SDK can better detect user activity and idle times to provide a better session rotation.
|
||||
|
||||
With swizzling disabled, the SDK only uses application open/backgrounded events to detect user activity, which can lead to a sub-optimal session calculation.
|
||||
|
||||
## Custom keyboard extensions
|
||||
|
||||
Custom keyboard extensions have stricter security rules than other extension types. To use PostHog in a custom keyboard, the keyboard must have [Open Access permission](https://developer.apple.com/documentation/uikit/configuring-open-access-for-a-custom-keyboard) enabled. This permission is required for network requests and write access to shared containers.
|
||||
|
||||
Users must explicitly grant Open Access in **Settings > General > Keyboard > Keyboards > [Your Keyboard] > Allow Full Access**.
|
||||
|
||||
## All configuration options
|
||||
|
||||
The [`PostHogConfig` object](https://github.com/PostHog/posthog.com/pull/13379/files?new_files_changed=true#r2480032424:~:text=gonna%20link%20to-,config%20object,-in%20posthog%20for) contains several other settings you can toggle:
|
||||
|
||||
| Attribute | Description |
|
||||
|-----------|-------------|
|
||||
| `flushAt`<br/><br/>**Type:** Integer<br/>**Default:** `20` | The number of queued events that the posthog client should flush at. Setting this to `1` will not queue any events and will use more battery. |
|
||||
| `flushIntervalSeconds`<br/><br/>**Type:** Integer<br/>**Default:** `30` | The amount of time to wait before each tick of the flush timer. Smaller values will make events delivered in a more real-time manner and also use more battery. A value smaller than 10 seconds will seriously degrade overall performance. |
|
||||
| `maxQueueSize`<br/><br/>**Type:** Integer<br/>**Default:** `1000` | The maximum number of items to queue before starting to drop old ones. This should be a value greater than zero, the behaviour is undefined otherwise. |
|
||||
| `maxBatchSize`<br/><br/>**Type:** Integer<br/>**Default:** `50` | Number of maximum events in a batch call. |
|
||||
| `captureApplicationLifecycleEvents`<br/><br/>**Type:** Boolean<br/>**Default:** `true` | Whether the posthog client should automatically make a capture call for application lifecycle events, such as "Application Installed", "Application Updated" and "Application Opened". |
|
||||
| `captureScreenViews`<br/><br/>**Type:** Boolean<br/>**Default:** `true` | Whether the posthog client should automatically make a screen call when a view controller is added to a view hierarchy. Because the underlying implementation uses method swizzling, we recommend initializing the posthog client as early as possible (before any screens are displayed), ideally during the Application delegate's applicationDidFinishLaunching method. |
|
||||
| `enableSwizzling`<br/><br/>**Type:** Boolean<br/>**Default:** `true` | Enable method swizzling for SDK functionality that depends on it. When disabled, functionality that requires swizzling (like autocapture, screen views, session replay, surveys) will not be installed. |
|
||||
| `captureElementInteractions`<br/><br/>**Type:** Boolean<br/>**Default:** `false` | (UIKit only) Whether the posthog client should automatically make a capture call when the user interacts with an element in a screen. |
|
||||
| `sendFeatureFlagEvent`<br/><br/>**Type:** Boolean<br/>**Default:** `true` | Send a `$feature_flag_called` event when a feature flag is used automatically. |
|
||||
| `preloadFeatureFlags`<br/><br/>**Type:** Boolean<br/>**Default:** `true` | Preload feature flags automatically. |
|
||||
| `evaluationEnvironments`<br/><br/>**Type:** Array of Strings<br/>**Default:** `undefined` | Environment tags that constrain which feature flags are evaluated. When set, only flags with matching evaluation tags (or no evaluation tags) will be returned. |
|
||||
| `debug`<br/><br/>**Type:** Boolean<br/>**Default:** `false` | Logs the SDK messages into Logcat. |
|
||||
| `optOut`<br/><br/>**Type:** Boolean<br/>**Default:** `false` | Prevents capturing any data if enabled. |
|
||||
| `getAnonymousId`<br/><br/>**Type:** Function<br/>**Default:** `undefined` | Hook that allows for modification of the default mechanism for generating anonymous id (which as of now is just random UUID v7). |
|
||||
| `dataMode`<br/><br/>**Type:** Enum<br/>**Default:** `.any` | Allows to send your data only if the data mode matches your configuration such as wifi only, cellular only or any. |
|
||||
| `personProfiles`<br/><br/>**Type:** Enum<br/>**Default:** `.identifiedOnly` | Determines the behavior for processing user profiles. |
|
||||
| `sessionReplay`<br/><br/>**Type:** Boolean<br/>**Default:** `false` | Enable Recording of Session Replays. |
|
||||
| `sessionReplayConfig`<br/><br/>**Type:** Object<br/>**Default:** `.init()` | Session Replay configuration. https://posthog.com/docs/session-replay/installation for more details |
|
||||
| `appGroupIdentifier`<br/><br/>**Type:** String<br/>**Default:** `nil` | The identifier of the App Group that should be used to store shared analytics data. PostHog will try to get the physical location of the App Group's shared container, otherwise fallback to the default location. |
|
||||
| `reuseAnonymousId`<br/><br/>**Type:** Boolean<br/>**Default:** `false` | Whether the SDK should reuse the anonymous Id between user changes. When enabled, a single Id will be used for all anonymous users on this device. |
|
||||
| `surveys`<br/><br/>**Type:** Boolean<br/>**Default:** `true` | Enable Surveys. |
|
||||
| `setBeforeSend`<br/><br/>**Type:** Function<br/>**Default:** `undefined` | Hook that allows for amending, sampling, or dropping events before they are sent to PostHog. |
|
||||
@@ -21,257 +21,14 @@ import IOSInstall from '../../integrate/_snippets/install-ios.mdx'
|
||||
import IOSIdentify from './_snippets/identify.mdx'
|
||||
import IOSSendEvents from '../../integrate/send-events/_snippets/send-events-ios.mdx'
|
||||
|
||||
This library uses an internal queue to make calls fast and non-blocking. It also batches requests and flushes asynchronously, making it perfect to use in any part of your mobile app.
|
||||
The PostHog iOS SDK is a library that you can use to track events, identify users, record session replays, evaluate feature flags, run experiments, build surveys, and more.
|
||||
|
||||
PostHog supports the following Apple platforms:
|
||||
|
||||
- **iOS:** Version 13 or later
|
||||
- **macOS:** Catalina (10.15) or later
|
||||
- **tvOS:** Version 13 or later
|
||||
- **watchOS:** Version 6 or later
|
||||
- **visionOS:** Version 1 or later
|
||||
This page shows you how to install the SDK and get started with it. If you've already installed the SDK, you can skip ahead to learn about [using the features](/docs/libraries/ios/usage) and [configuring the SDK](/docs/libraries/ios/configuration).
|
||||
|
||||
## Installation
|
||||
|
||||
<IOSInstall />
|
||||
|
||||
## Capturing events
|
||||
|
||||
<IOSSendEvents />
|
||||
|
||||
## Preventing sensitive data capture
|
||||
|
||||
To exclude specific UI elements from autocapture or session replay, add `ph-no-capture` as either an `accessibilityLabel` or `accessibilityIdentifier`. When PostHog detects this label or identifier anywhere in the view hierarchy, the element will be either ignored or masked:
|
||||
|
||||
```swift
|
||||
// This view will be excluded from autocapture
|
||||
let view = UIView()
|
||||
view.accessibilityLabel = "ph-no-capture"
|
||||
```
|
||||
|
||||
> **Important:** By default, PostHog will make a best effort to automatically exclude fields detected as sensitive, even without the `ph-no-capture` tag. These include password fields, credit card fields, OTP fields, and any other fields related to Personally Identifiable Information (PII).
|
||||
|
||||
For more details on how to setup masking for session replay, please refer to our [Privacy Controls](/docs/session-replay/privacy?tab=iOS) documentation.
|
||||
|
||||
## Identifying users
|
||||
|
||||
> We highly recommend reading our section on [Identifying users](/docs/integrate/identifying-users) to better understand how to correctly use this method.
|
||||
|
||||
<IOSIdentify />
|
||||
|
||||
## Get the current user's distinct ID
|
||||
|
||||
You may find it helpful to get the current user's distinct ID. For example, to check whether you've already called `identify` for a user or not.
|
||||
|
||||
To do this, call `getDistinctId()`. This returns either the ID automatically generated by PostHog or the ID that has been passed by a call to `identify()`.
|
||||
|
||||
## Alias
|
||||
|
||||
Sometimes, you want to assign multiple distinct IDs to a single user. This is helpful when your primary distinct ID is inaccessible. For example, if a distinct ID used on the frontend is not available in your backend.
|
||||
|
||||
In this case, you can use `alias` to assign another distinct ID to the same user.
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.alias("alias_id")
|
||||
```
|
||||
|
||||
We strongly recommend reading our docs on [alias](/docs/data/identify#alias-assigning-multiple-distinct-ids-to-the-same-user) to best understand how to correctly use this method.
|
||||
|
||||
## Anonymous vs identified events
|
||||
|
||||
import IdentifiedVsAnonymousIntro from '../../product-analytics/_snippets/identified-vs-anonymous-intro.mdx'
|
||||
|
||||
<IdentifiedVsAnonymousIntro />
|
||||
|
||||
### How to capture anonymous events
|
||||
|
||||
import HowToCaptureAnonymousEventsIOS from '../../product-analytics/_snippets/how-to-capture-anonymous-events-ios.mdx'
|
||||
|
||||
<HowToCaptureAnonymousEventsIOS />
|
||||
|
||||
### How to capture identified events
|
||||
|
||||
import HowToCaptureIdentifiedEventsIOS from '../../product-analytics/_snippets/how-to-capture-identified-events-ios.mdx'
|
||||
|
||||
<HowToCaptureIdentifiedEventsIOS />
|
||||
|
||||
## Setting person properties
|
||||
|
||||
To set [properties](/docs/data/user-properties) on your users via an event, you can leverage the event properties `userProperties` and `userPropertiesSetOnce`.
|
||||
|
||||
When capturing an event, you can pass a property called `$set` as an event property, and specify its value to be an object with properties to be set on the user that will be associated with the user who triggered the event.
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.capture("signed_up", properties: ["plan": "Pro++"], userProperties: ["user_property_name": "your_value"])
|
||||
```
|
||||
|
||||
`userPropertiesSetOnce` works just like `userProperties`, except that it will **only set the property if the user doesn't already have that property set**.
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.capture("signed_up", properties: ["plan": "Pro++"], userPropertiesSetOnce: ["user_property_name": "your_value"])
|
||||
```
|
||||
|
||||
## Super Properties
|
||||
|
||||
Super Properties are properties associated with events that are set once and then sent with every `capture` call, be it a `$screen`, or anything else.
|
||||
|
||||
They are set using `PostHogSDK.shared.register`, which takes a properties object as a parameter, and they persist across sessions.
|
||||
|
||||
For example, take a look at the following call:
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.register(["team_id": 22])
|
||||
```
|
||||
|
||||
The call above ensures that every event sent by the user will include `"team_id": 22`. This way, if you filtered events by property using `team_id = 22`, it would display all events captured on that user after the `PostHogSDK.shared.register` call, since they all include the specified Super Property.
|
||||
|
||||
However, please note that this does not store properties against the User, only against their events. To store properties against the User object, you should use `PostHogSDK.shared.identify`. More information on this can be found on the [Sending User Information section](#sending-user-information).
|
||||
|
||||
### Removing stored Super Properties
|
||||
|
||||
Super Properties are persisted across sessions so you have to explicitly remove them if they are no longer relevant. In order to stop sending a Super Property with events, you can use `PostHogSDK.shared.unregister`, like so:
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.unregister("team_id")
|
||||
```
|
||||
|
||||
This will remove the Super Property and subsequent events will not include it.
|
||||
|
||||
If you are doing this as part of a user logging out you can instead simply use `PostHogSDK.shared.reset` which takes care of clearing all stored Super Properties and more.
|
||||
|
||||
## Amending, dropping or sampling events
|
||||
|
||||
Since version 3.28.0, you can provide a `BeforeSendBlock` function when initializing the SDK to amend, drop or sample events before they are sent to PostHog.
|
||||
|
||||
> **⚠️ Note:** This replaces the deprecated `propertiesSanitizer` option and provides more flexibility in modifying events. You can achieve the same functionality as `propertiesSanitizer` by using a `BeforeSendBlock` that mutates the event's properties in place.
|
||||
|
||||
> **🚨 Warning:** Amending and sampling events is advanced functionality that requires careful implementation. Core PostHog features may require 100% of unmodified events to function properly. We recommend only modifying or sampling your own custom events if possible, and preserving all PostHog internal events in their original form.
|
||||
|
||||
### Redacting information in events
|
||||
|
||||
`BeforeSendBlock` gives you one place to edit or redact information before it is sent to PostHog. For example:
|
||||
|
||||
<details>
|
||||
<summary>Redact URLs in event properties</summary>
|
||||
|
||||
```swift
|
||||
let config = PostHogConfig(apiKey: "<ph_project_api_key>", host: "<ph_api_client_host>")
|
||||
|
||||
config.setBeforeSend { event in
|
||||
// Redact URLs
|
||||
if let url = event.properties["url"] as? String {
|
||||
event.properties["url"] = url.map { _ in "*" }.joined()
|
||||
}
|
||||
return event
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Redact sensitive information from event properties</summary>
|
||||
|
||||
```swift
|
||||
let config = PostHogConfig(apiKey: "<ph_project_api_key>", host: "<ph_api_client_host>")
|
||||
|
||||
config.setBeforeSend { event in
|
||||
// Redact sensitive information
|
||||
if let email = event.properties["email"] as? String {
|
||||
event.properties["email"] = email.map { _ in "*" }.joined()
|
||||
}
|
||||
|
||||
return event
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Drop events by event name</summary>
|
||||
|
||||
```swift
|
||||
let config = PostHogConfig(apiKey: "<ph_project_api_key>", host: "<ph_api_client_host>")
|
||||
|
||||
config.setBeforeSend { event in
|
||||
// Drop all events named "Stale Event"
|
||||
if event.event == "Stale Event" {
|
||||
return nil
|
||||
}
|
||||
return event
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
### Sampling events
|
||||
|
||||
Sampling lets you choose to send only a percentage of events to PostHog. It is a good way to control your costs without having to completely turn off features of the SDK.
|
||||
|
||||
<details>
|
||||
<summary>Sample events by event name</summary>
|
||||
|
||||
```swift
|
||||
let config = PostHogConfig(apiKey: "<ph_project_api_key>", host: "<ph_api_client_host>")
|
||||
|
||||
config.setBeforeSend { event in
|
||||
// Sample 10% of Sampled Event events
|
||||
if event.event == "Sampled Event" {
|
||||
if Double.random(in: 0...1) < 0.1 {
|
||||
event.properties["$sample_type"] = ["sampleByEvent"]
|
||||
event.properties["$sample_threshold"] = 0.1
|
||||
event.properties["$sampled_events"] = ["Sampled Event"]
|
||||
return event
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return event
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
### Chaining multiple BeforeSendBlocks
|
||||
|
||||
You can provide an array of `BeforeSendBlock` functions to be called one after the other:
|
||||
|
||||
```swift
|
||||
let config = PostHogConfig(apiKey: "<ph_project_api_key>", host: "<ph_api_client_host>")
|
||||
|
||||
config.setBeforeSend(
|
||||
// First block: Drop all events named "Stale Event"
|
||||
{ event in
|
||||
if event.event == "Stale Event" {
|
||||
return nil
|
||||
}
|
||||
return event
|
||||
},
|
||||
// Second block: Redact sensitive information
|
||||
{ event in
|
||||
if let email = event.properties["email"] as? String {
|
||||
event.properties["email"] = email.map { _ in "*" }.joined()
|
||||
}
|
||||
return event
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
**Note:** When chaining beforeSend blocks, order is important. The first block is executed first and the mutated event is passed along to the second block, and so on. If at any point in the chain the event is dropped, any subsequent blocks will not be executed.
|
||||
|
||||
## Flush
|
||||
|
||||
You can set the number of events in the configuration that should queue before flushing.
|
||||
Setting this to `1` will send events immediately and will use more battery. This is set to `20` by default.
|
||||
|
||||
```swift
|
||||
configuration.flushAt = 1
|
||||
```
|
||||
|
||||
You can also manually flush the queue:
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.capture("logged_out")
|
||||
PostHogSDK.shared.flush()
|
||||
```
|
||||
|
||||
## Offline behavior
|
||||
|
||||
The PostHog iOS SDK will continue to capture events when the device is offline. The events are stored in a queue in the device's file storage and are flushed when the device is online.
|
||||
@@ -280,131 +37,7 @@ The PostHog iOS SDK will continue to capture events when the device is offline.
|
||||
- When the queue is full, the oldest event is deleted first.
|
||||
- The queue is flushed only when the device is online.
|
||||
|
||||
## Reset after logout
|
||||
|
||||
To reset the user's ID and anonymous ID, call `reset`. Usually you would do this right after the user logs out.
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.reset()
|
||||
```
|
||||
|
||||
## Opt out of data capture
|
||||
|
||||
You can completely opt-out users from data capture. To do this, there are two options:
|
||||
|
||||
1. Opt users out by default by setting `optOut` to `true` in your PostHog config:
|
||||
|
||||
```swift
|
||||
let config = PostHogConfig(apiKey: "<ph_project_api_key>", host: "<ph_client_api_host>")
|
||||
config.optOut = true
|
||||
PostHogSDK.shared.setup(config)
|
||||
```
|
||||
|
||||
2. Opt users out on a per-person basis by calling `optOut()`:
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.optOut()
|
||||
```
|
||||
|
||||
Similarly, you can opt users in:
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.optIn()
|
||||
```
|
||||
|
||||
To check if a user is opted out:
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.isOptOut()
|
||||
```
|
||||
|
||||
## Group analytics
|
||||
|
||||
Group analytics allows you to associate the events for that person's session with a group (e.g. teams, organizations, etc.). Read the [Group Analytics](/docs/user-guides/group-analytics) guide for more information.
|
||||
|
||||
> **Note: ** This is a paid feature and is not available on the open-source or free cloud plan. Learn more [here](/pricing).
|
||||
|
||||
- Associate the events for this session with a group
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.group(type: "company", key: "company_id_in_your_db")
|
||||
```
|
||||
|
||||
- Associate the events for this session with a group AND update the properties of that group
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.group(type: "company", key: "company_id_in_your_db", groupProperties: [
|
||||
"name": "ACME Corp"
|
||||
])
|
||||
```
|
||||
|
||||
The `name` is a special property which is used in the PostHog UI for the name of the group. If you don't specify a `name` property, the group ID will be used instead.
|
||||
|
||||
## Feature Flags
|
||||
|
||||
import FeatureFlagsLibsIntro from "../_snippets/feature-flags-libs-intro.mdx"
|
||||
|
||||
<FeatureFlagsLibsIntro />
|
||||
|
||||
import IOSFeatureFlagsCode from '../../integrate/feature-flags-code/_snippets/feature-flags-code-ios.mdx'
|
||||
|
||||
<IOSFeatureFlagsCode />
|
||||
|
||||
## Experiments (A/B tests)
|
||||
|
||||
Since [experiments](/docs/experiments/manual) use feature flags, the code for running an experiment is very similar to the feature flags code:
|
||||
|
||||
```swift
|
||||
if (PostHogSDK.shared.getFeatureFlag("experiment-feature-flag-key") as? String == "variant-name") {
|
||||
// do something
|
||||
}
|
||||
```
|
||||
|
||||
It's also possible to [run experiments without using feature flags](/docs/experiments/running-experiments-without-feature-flags).
|
||||
|
||||
## A note about IDFA (identifier for advertisers) collection in iOS 14
|
||||
|
||||
Starting with iOS 14, Apple will further restrict apps that track users. Any references to Apple's AdSupport framework, even in strings, [will trip](https://github.com/PostHog/posthog-ios/issues/6) the App Store's static analysis.
|
||||
|
||||
Hence **starting with posthog-ios version 1.2.0** we have removed all references to Apple's AdSupport framework.
|
||||
|
||||
## Session replay
|
||||
|
||||
> **Note:** Session replay is currently only available on iOS. For future macOS support, please follow and upvote [this GitHub issue](https://github.com/PostHog/posthog-ios/issues/200).
|
||||
|
||||
To set up [session replay](/docs/session-replay/mobile) in your project, all you need to do is install the iOS SDK, enable "Record user sessions" in [your project settings](https://us.posthog.com/settings/project-replay) and enable the `sessionReplay` option.
|
||||
|
||||
## Surveys
|
||||
|
||||
[Surveys](/docs/surveys) launched with [popover presentation](/docs/surveys/creating-surveys#presentation) are automatically shown to users matching the [display conditions](/docs/surveys/creating-surveys#display-conditions) you set up.
|
||||
|
||||
## Method swizzling
|
||||
|
||||
The PostHog iOS SDK uses method swizzling to intercept and modify method calls at runtime to provide advanced features like:
|
||||
|
||||
- **Screen view tracking** - Automatically captures when view controllers are presented (`config.captureScreenViews`)
|
||||
- **Element interactions** - Automatically tracks user interactions with UI elements (`config.captureElementInteractions`)
|
||||
- **Session replay** - Records user sessions (`config.sessionReplay`)
|
||||
- **Surveys** - Displays surveys at appropriate times (`config.surveys`)
|
||||
- **Advanced metrics tracking** - Provides more precise session ID calculation and rotation by detecting user activity and idleness
|
||||
|
||||
### Disabling method swizzling
|
||||
|
||||
Since version 3.34.0, you can opt out of swizzling using the `enableSwizzling` configuration option. When you disable swizzling, the SDK disables the features listed above.
|
||||
|
||||
```swift
|
||||
let config = PostHogConfig(apiKey: "<ph_project_api_key>", host: "<ph_api_client_host>")
|
||||
config.enableSwizzling = false
|
||||
PostHogSDK.shared.setup(config)
|
||||
```
|
||||
|
||||
> **Note:** When method swizzling is disabled, features that depend on it will not work even if they are individually enabled in the config. For example, if you set `config.sessionReplay = true` and `config.enableSwizzling = false`, session replay will **not** be enabled.
|
||||
|
||||
### Session metrics management
|
||||
|
||||
Method swizzling is particularly important for accurate [session metrics tracking](/tutorials/session-metrics). With swizzling enabled, the SDK can better detect user activity and idle times to provide a better session rotation.
|
||||
|
||||
With swizzling disabled, the SDK only uses application open/backgrounded events to detect user activity, which can lead to a sub-optimal session calculation.
|
||||
You can find the options for configuring the offline behavior in the [configuration page](/docs/libraries/ios/configuration#all-configuration-options).
|
||||
|
||||
## Using PostHog with application extensions
|
||||
|
||||
@@ -416,158 +49,19 @@ By default, each iOS app target stores its data in its own sandboxed directory.
|
||||
- Fragmented user journeys
|
||||
- Difficulty tracking feature adoption across your app ecosystem
|
||||
|
||||
### Setup
|
||||
[Learn more about setting up app groups](/docs/libraries/ios/configuration#setting-up-app-groups).
|
||||
|
||||
1. **Configure App Groups**: Set up an [App Group](https://developer.apple.com/documentation/xcode/configuring-app-groups) in Xcode for your main app and extension targets
|
||||
2. **Configure PostHog**: Use the same App Group identifier in all targets:
|
||||
## Method swizzling
|
||||
|
||||
```swift
|
||||
let config = PostHogConfig(apiKey: "<ph_project_api_key>", host: "<ph_api_client_host>")
|
||||
config.appGroupIdentifier = "group.com.yourcompany.yourapp"
|
||||
PostHogSDK.shared.setup(config)
|
||||
```
|
||||
The PostHog iOS SDK uses method swizzling to intercept and modify method calls at runtime to provide advanced features like screen view tracking, element interactions, session replay, surveys, and more.
|
||||
|
||||
### Custom keyboard extensions
|
||||
Method swizzling is particularly important for accurate session metrics tracking. When disabled, the SDK cannot capture optimal session metrics.
|
||||
|
||||
Custom keyboard extensions have stricter security rules than other extension types. To use PostHog analytics in a custom keyboard, the keyboard must have [Open Access permission](https://developer.apple.com/documentation/uikit/configuring-open-access-for-a-custom-keyboard) enabled. This permission is required for network requests and write access to shared containers.
|
||||
You can learn more about configuring method swizzling in the [configuration page](/docs/libraries/ios/configuration#method-swizzling).
|
||||
|
||||
Users must explicitly grant Open Access in **Settings > General > Keyboard > Keyboards > [Your Keyboard] > Allow Full Access**.
|
||||
## Next steps
|
||||
|
||||
## All configuration options
|
||||
Now that you've installed the SDK, explore the configuration and usage options:
|
||||
|
||||
The `configuration` element contains several other settings you can toggle:
|
||||
|
||||
```swift
|
||||
/**
|
||||
* The number of queued events that the posthog client should flush at. Setting this to `1` will not queue
|
||||
* any events and will use more battery. `20` by default.
|
||||
*/
|
||||
configuration.flushAt = 20
|
||||
|
||||
/**
|
||||
* The amount of time to wait before each tick of the flush timer.
|
||||
* Smaller values will make events delivered in a more real-time manner and also use more battery.
|
||||
* A value smaller than 10 seconds will seriously degrade overall performance.
|
||||
* 30 seconds by default.
|
||||
*/
|
||||
configuration.flushIntervalSeconds = 30
|
||||
|
||||
/**
|
||||
* The maximum number of items to queue before starting to drop old ones. This should be a value greater
|
||||
* than zero, the behaviour is undefined otherwise. `1000` by default.
|
||||
*/
|
||||
configuration.maxQueueSize = 1000
|
||||
|
||||
/**
|
||||
* Number of maximum events in a batch call. (50 by default)
|
||||
*/
|
||||
configuration.maxBatchSize = 50
|
||||
|
||||
/**
|
||||
* Whether the posthog client should automatically make a capture call for application lifecycle events,
|
||||
* such as "Application Installed", "Application Updated" and "Application Opened". (on/true by default)
|
||||
*/
|
||||
configuration.captureApplicationLifecycleEvents = true
|
||||
|
||||
/**
|
||||
* Whether the posthog client should automatically make a screen call when a view controller is added to
|
||||
* a view hierarchy. Because the underlying implementation uses method swizzling, we recommend initializing
|
||||
* the posthog client as early as possible (before any screens are displayed), ideally during the
|
||||
* Application delegate's applicationDidFinishLaunching method. (on/true by default)
|
||||
*/
|
||||
configuration.captureScreenViews = true
|
||||
|
||||
/**
|
||||
* Enable method swizzling for SDK functionality that depends on it. When disabled, functionality that
|
||||
* requires swizzling (like autocapture, screen views, session replay, surveys) will not be installed.
|
||||
* (on/true by default)
|
||||
*/
|
||||
configuration.enableSwizzling = true
|
||||
|
||||
/**
|
||||
* (UIKit only) Whether the posthog client should automatically make a capture call when the user interacts with an element in a screen.
|
||||
*
|
||||
* Defaults to false
|
||||
*/
|
||||
configuration.captureElementInteractions = false
|
||||
|
||||
/**
|
||||
* Send a `$feature_flag_called` event when a feature flag is used automatically. (on/true by default)
|
||||
*/
|
||||
configuration.sendFeatureFlagEvent = true
|
||||
|
||||
/**
|
||||
* Preload feature flags automatically. (on/true by default)
|
||||
*/
|
||||
configuration.preloadFeatureFlags = true
|
||||
|
||||
/**
|
||||
* Environment tags that constrain which feature flags are evaluated. (not set by default)
|
||||
* When set, only flags with matching evaluation tags (or no evaluation tags) will be returned.
|
||||
*/
|
||||
configuration.evaluationEnvironments = ["production", "ios", "mobile"]
|
||||
|
||||
/**
|
||||
* Logs the SDK messages into Logcat. (off/false by default)
|
||||
*/
|
||||
configuration.debug = false
|
||||
|
||||
/**
|
||||
* Prevents capturing any data if enabled. (off/false by default)
|
||||
*/
|
||||
configuration.optOut = false
|
||||
|
||||
/**
|
||||
* Hook that allows for modification of the default mechanism for
|
||||
* generating anonymous id (which as of now is just random UUID v7)
|
||||
*/
|
||||
configuration.getAnonymousId = { ... }
|
||||
|
||||
/**
|
||||
* Allows to send your data only if the data mode matches your configuration
|
||||
* such as wifi only, cellular only or any.
|
||||
* Defaults to .any
|
||||
*/
|
||||
configuration.dataMode = .any
|
||||
|
||||
/**
|
||||
* Determines the behavior for processing user profiles.
|
||||
* Defaults to .identifiedOnly
|
||||
*/
|
||||
configuration.personProfiles = .identifiedOnly
|
||||
|
||||
/**
|
||||
* Enable Recording of Session Replays. (off/false by default)
|
||||
*/
|
||||
configuration.sessionReplay = false
|
||||
|
||||
/**
|
||||
* Session Replay configuration
|
||||
* https://posthog.com/docs/session-replay/installation for more details
|
||||
*/
|
||||
configuration.sessionReplayConfig = .init()
|
||||
|
||||
/**
|
||||
* The identifier of the App Group that should be used to store shared analytics data.
|
||||
* PostHog will try to get the physical location of the App Group’s shared container, otherwise fallback to the default location
|
||||
*/
|
||||
configuration.appGroupIdentifier = nil
|
||||
|
||||
/**
|
||||
* Whether the SDK should reuse the anonymous Id between user changes.
|
||||
* When enabled, a single Id will be used for all anonymous users on this device
|
||||
* Defaults to false
|
||||
*/
|
||||
configuration.reuseAnonymousId = false
|
||||
|
||||
|
||||
/**
|
||||
* Enable Surveys. (on/true by default)
|
||||
*/
|
||||
configuration.surveys = true
|
||||
|
||||
/**
|
||||
* Hook that allows for amending, sampling, or dropping events before they are sent to PostHog.
|
||||
*/
|
||||
configuration.setBeforeSend { ... }
|
||||
```
|
||||
- [Learn about using all of the features of PostHog with iOS SDK](/docs/libraries/ios/usage)
|
||||
- [Learn about configuration options for the iOS SDK](/docs/libraries/ios/configuration)
|
||||
224
contents/docs/libraries/ios/usage.mdx
Normal file
224
contents/docs/libraries/ios/usage.mdx
Normal file
@@ -0,0 +1,224 @@
|
||||
---
|
||||
title: iOS SDK usage
|
||||
sidebarTitle: iOS
|
||||
sidebar: Docs
|
||||
showTitle: true
|
||||
github: 'https://github.com/PostHog/posthog-ios'
|
||||
icon: >-
|
||||
https://res.cloudinary.com/dmukukwp6/image/upload/posthog.com/contents/images/docs/integrate/ios.svg
|
||||
features:
|
||||
eventCapture: true
|
||||
userIdentification: true
|
||||
autoCapture: true
|
||||
sessionRecording: true
|
||||
featureFlags: true
|
||||
groupAnalytics: true
|
||||
surveys: true
|
||||
llmAnalytics: false
|
||||
---
|
||||
|
||||
import IOSIdentify from './_snippets/identify.mdx'
|
||||
import IOSSendEvents from '../../integrate/send-events/_snippets/send-events-ios.mdx'
|
||||
|
||||
|
||||
## Capturing events
|
||||
|
||||
<IOSSendEvents />
|
||||
|
||||
## Preventing sensitive data capture
|
||||
|
||||
To exclude specific UI elements from autocapture or session replay, add `ph-no-capture` as either an `accessibilityLabel` or `accessibilityIdentifier`. When PostHog detects this label or identifier anywhere in the view hierarchy, the element will be either ignored or masked:
|
||||
|
||||
```swift
|
||||
// This view will be excluded from autocapture
|
||||
let view = UIView()
|
||||
view.accessibilityLabel = "ph-no-capture"
|
||||
```
|
||||
|
||||
> **Important:** By default, PostHog will make a best effort to automatically exclude fields detected as sensitive, even without the `ph-no-capture` tag. These include password fields, credit card fields, OTP fields, and any other fields related to Personally Identifiable Information (PII).
|
||||
|
||||
For more details on how to setup masking for session replay, please refer to our [privacy controls](/docs/session-replay/privacy?tab=iOS) documentation.
|
||||
|
||||
## Identifying users
|
||||
|
||||
> We highly recommend reading our section on [Identifying users](/docs/integrate/identifying-users) to better understand how to correctly use this method.
|
||||
|
||||
<IOSIdentify />
|
||||
|
||||
## Get the current user's distinct ID
|
||||
|
||||
You may find it helpful to get the current user's distinct ID. For example, to check whether you've already called `identify` for a user or not.
|
||||
|
||||
To do this, call `getDistinctId()`. This returns either the ID automatically generated by PostHog or the ID that has been passed by a call to `identify()`.
|
||||
|
||||
## Alias
|
||||
|
||||
Sometimes, you want to assign multiple distinct IDs to a single user. This is helpful when your primary distinct ID is inaccessible. For example, if a distinct ID used on the frontend is not available in your backend.
|
||||
|
||||
In this case, you can use `alias` to assign another distinct ID to the same user.
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.alias("alias_id")
|
||||
```
|
||||
|
||||
We strongly recommend reading our docs on [alias](/docs/data/identify#alias-assigning-multiple-distinct-ids-to-the-same-user) to best understand how to correctly use this method.
|
||||
|
||||
## Anonymous vs identified events
|
||||
|
||||
import IdentifiedVsAnonymousIntro from '../../product-analytics/_snippets/identified-vs-anonymous-intro.mdx'
|
||||
|
||||
<IdentifiedVsAnonymousIntro />
|
||||
|
||||
### How to capture anonymous events
|
||||
|
||||
import HowToCaptureAnonymousEventsIOS from '../../product-analytics/_snippets/how-to-capture-anonymous-events-ios.mdx'
|
||||
|
||||
<HowToCaptureAnonymousEventsIOS />
|
||||
|
||||
### How to capture identified events
|
||||
|
||||
import HowToCaptureIdentifiedEventsIOS from '../../product-analytics/_snippets/how-to-capture-identified-events-ios.mdx'
|
||||
|
||||
<HowToCaptureIdentifiedEventsIOS />
|
||||
|
||||
## Setting person properties
|
||||
|
||||
To set [properties](/docs/data/user-properties) on your users via an event, you can leverage the event properties `userProperties` and `userPropertiesSetOnce`.
|
||||
|
||||
When capturing an event, you can pass a property called `$set` as an event property, and specify its value to be an object with properties to be set on the user that will be associated with the user who triggered the event.
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.capture("signed_up", properties: ["plan": "Pro++"], userProperties: ["user_property_name": "your_value"])
|
||||
```
|
||||
|
||||
`userPropertiesSetOnce` works just like `userProperties`, except that it will **only set the property if the user doesn't already have that property set**.
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.capture("signed_up", properties: ["plan": "Pro++"], userPropertiesSetOnce: ["user_property_name": "your_value"])
|
||||
```
|
||||
|
||||
## Super properties
|
||||
|
||||
Super properties are properties associated with events that are set once and then sent with every `capture` call, be it a `$screen`, or anything else.
|
||||
|
||||
They are set using `PostHogSDK.shared.register`, which takes a properties object as a parameter, and they persist across sessions.
|
||||
|
||||
For example, take a look at the following call:
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.register(["team_id": 22])
|
||||
```
|
||||
|
||||
The call above ensures that every event sent by the user will include `"team_id": 22`. This way, if you filtered events by property using `team_id = 22`, it would display all events captured on that user after the `PostHogSDK.shared.register` call, since they all include the specified Super Property.
|
||||
|
||||
However, please note that this does not store properties against the User, only against their events. To store properties against the User object, you should use `PostHogSDK.shared.identify`. More information on this can be found on the [Sending User Information section](#sending-user-information).
|
||||
|
||||
### Removing stored super properties
|
||||
|
||||
Super properties persist across sessions so you have to explicitly remove them if they are no longer relevant. To stop sending a super property with events, you can use `PostHogSDK.shared.unregister`, like so:
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.unregister("team_id")
|
||||
```
|
||||
|
||||
This removes the super property and subsequent events will not include it.
|
||||
|
||||
If you are doing this as part of a user logging out, you can instead simply use `PostHogSDK.shared.reset` which clears all super properties and more.
|
||||
|
||||
## Reset after logout
|
||||
|
||||
To reset the user's ID and anonymous ID, call `reset`. Usually you would do this right after the user logs out.
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.reset()
|
||||
```
|
||||
|
||||
## Group analytics
|
||||
|
||||
Group analytics allows you to associate the events for that person's session with a group (e.g. teams, organizations, etc.). Read the [Group Analytics](/docs/user-guides/group-analytics) guide for more information.
|
||||
|
||||
> **Note: ** This is a paid feature and is not available on the open-source or free cloud plan. Learn more [here](/pricing).
|
||||
|
||||
- Associate the events for this session with a group
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.group(type: "company", key: "company_id_in_your_db")
|
||||
```
|
||||
|
||||
- Associate the events for this session with a group AND update the properties of that group
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.group(type: "company", key: "company_id_in_your_db", groupProperties: [
|
||||
"name": "ACME Corp"
|
||||
])
|
||||
```
|
||||
|
||||
The `name` is a special property which is used in the PostHog UI for the name of the group. If you don't specify a `name` property, the group ID will be used instead.
|
||||
|
||||
## Opt out of data capture
|
||||
|
||||
You can completely opt-out users from data capture. To do this, there are two options:
|
||||
|
||||
1. Opt users out by default by setting `optOut` to `true` in your PostHog config:
|
||||
|
||||
```swift
|
||||
let config = PostHogConfig(apiKey: "<ph_project_api_key>", host: "<ph_client_api_host>")
|
||||
config.optOut = true
|
||||
PostHogSDK.shared.setup(config)
|
||||
```
|
||||
|
||||
2. Opt users out on a per-person basis by calling `optOut()`:
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.optOut()
|
||||
```
|
||||
|
||||
Similarly, you can opt users in:
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.optIn()
|
||||
```
|
||||
|
||||
To check if a user is opted out:
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.isOptOut()
|
||||
```
|
||||
|
||||
## Feature flags
|
||||
|
||||
import FeatureFlagsLibsIntro from "../_snippets/feature-flags-libs-intro.mdx"
|
||||
|
||||
<FeatureFlagsLibsIntro />
|
||||
|
||||
import IOSFeatureFlagsCode from '../../integrate/feature-flags-code/_snippets/feature-flags-code-ios.mdx'
|
||||
|
||||
<IOSFeatureFlagsCode />
|
||||
|
||||
## Experiments (A/B tests)
|
||||
|
||||
Since [experiments](/docs/experiments/manual) use feature flags, the code for running an experiment is very similar to the feature flags code:
|
||||
|
||||
```swift
|
||||
if (PostHogSDK.shared.getFeatureFlag("experiment-feature-flag-key") as? String == "variant-name") {
|
||||
// do something
|
||||
}
|
||||
```
|
||||
|
||||
It's also possible to [run experiments without using feature flags](/docs/experiments/running-experiments-without-feature-flags).
|
||||
|
||||
## A note about IDFA (identifier for advertisers) collection in iOS 14
|
||||
|
||||
Starting with iOS 14, Apple will further restrict apps that track users. Any references to Apple's AdSupport framework, even in strings, [will trip](https://github.com/PostHog/posthog-ios/issues/6) the App Store's static analysis.
|
||||
|
||||
Hence **starting with posthog-ios version 1.2.0** we have removed all references to Apple's AdSupport framework.
|
||||
|
||||
## Session replay
|
||||
|
||||
> **Note:** Session replay is currently only available on iOS. For future macOS support, please follow and upvote [this GitHub issue](https://github.com/PostHog/posthog-ios/issues/200).
|
||||
|
||||
To set up [session replay](/docs/session-replay/mobile) in your project, all you need to do is install the iOS SDK, enable "Record user sessions" in [your project settings](https://us.posthog.com/settings/project-replay) and enable the `sessionReplay` option.
|
||||
|
||||
## Surveys
|
||||
|
||||
[Surveys](/docs/surveys) launched with [popover presentation](/docs/surveys/creating-surveys#presentation) are automatically shown to users matching the [display conditions](/docs/surveys/creating-surveys#display-conditions) you set up.
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: JavaScript Web configuration
|
||||
title: JavaScript web configuration
|
||||
sidebar: Docs
|
||||
showTitle: true
|
||||
---
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: JavaScript Web
|
||||
sidebarTitle: JavaScript Web
|
||||
title: JavaScript web
|
||||
sidebarTitle: JavaScript web
|
||||
sidebar: Docs
|
||||
showTitle: true
|
||||
github: 'https://github.com/PostHog/posthog-js'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: Managing persistence and cookies
|
||||
title: JavaScript web persistence and cookies
|
||||
sidebar: Docs
|
||||
showTitle: true
|
||||
---
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: JavaScript Web features
|
||||
title: JavaScript web usage
|
||||
sidebar: Docs
|
||||
showTitle: true
|
||||
---
|
||||
@@ -1,4 +1,4 @@
|
||||
The iOS SDK captures anonymous events by default. However, this may change depending on your `personProfiles` [config](/docs/libraries/ios#all-configuration-options) when initializing PostHog:
|
||||
The iOS SDK captures anonymous events by default. However, this may change depending on your `personProfiles` [config](/docs/libraries/ios/configuration#all-configuration-options) when initializing PostHog:
|
||||
|
||||
1. `personProfiles: .identifiedOnly` _(recommended)_ _(default)_ - Anonymous events are captured by default. PostHog only captures identified events for users where [person profiles](/docs/data/persons) have already been created.
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
If you've set the [`personProfiles` config](/docs/libraries/ios#all-configuration-options) to `IDENTIFIED_ONLY` (the default option), anonymous events are captured by default. Then, to capture identified events, call any of the following functions:
|
||||
If you've set the [`personProfiles` config](/docs/libraries/ios/configuration#all-configuration-options) to `IDENTIFIED_ONLY` (the default option), anonymous events are captured by default. Then, to capture identified events, call any of the following functions:
|
||||
|
||||
- [`identify()`](/docs/product-analytics/identify)
|
||||
- [`alias()`](/docs/product-analytics/identify#alias-assigning-multiple-distinct-ids-to-the-same-user)
|
||||
|
||||
@@ -1835,8 +1835,8 @@ export const docsMenu = {
|
||||
url: '/docs/libraries/js',
|
||||
},
|
||||
{
|
||||
name: 'Features',
|
||||
url: '/docs/libraries/js/features',
|
||||
name: 'Usage',
|
||||
url: '/docs/libraries/js/usage',
|
||||
},
|
||||
{
|
||||
name: 'Configuration',
|
||||
@@ -1886,6 +1886,20 @@ export const docsMenu = {
|
||||
title: 'Popular',
|
||||
className: '!bg-blue/10 !text-blue !dark:text-white !dark:bg-blue/50',
|
||||
},
|
||||
children: [
|
||||
{
|
||||
name: 'Installation',
|
||||
url: '/docs/libraries/ios',
|
||||
},
|
||||
{
|
||||
name: 'Usage',
|
||||
url: '/docs/libraries/ios/usage',
|
||||
},
|
||||
{
|
||||
name: 'Configuration',
|
||||
url: '/docs/libraries/ios/configuration',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Java',
|
||||
@@ -1900,7 +1914,7 @@ export const docsMenu = {
|
||||
url: '/docs/libraries/node',
|
||||
children: [
|
||||
{
|
||||
name: 'Setup and features',
|
||||
name: 'Setup and usage',
|
||||
url: '/docs/libraries/node',
|
||||
},
|
||||
{
|
||||
@@ -1918,7 +1932,7 @@ export const docsMenu = {
|
||||
url: '/docs/libraries/python',
|
||||
children: [
|
||||
{
|
||||
name: 'Setup and features',
|
||||
name: 'Setup and usage',
|
||||
url: '/docs/libraries/python',
|
||||
},
|
||||
{
|
||||
@@ -1944,7 +1958,7 @@ export const docsMenu = {
|
||||
},
|
||||
children: [
|
||||
{
|
||||
name: 'Setup and features',
|
||||
name: 'Setup and usage',
|
||||
url: '/docs/libraries/react-native',
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1631,6 +1631,10 @@
|
||||
"source": "/docs/max-ai",
|
||||
"destination": "/docs/posthog-ai"
|
||||
},
|
||||
{
|
||||
"source": "/docs/libraries/js/features",
|
||||
"destination": "/docs/libraries/js/usage"
|
||||
},
|
||||
{
|
||||
"source": "/handbook/engineering/on-call-rotation",
|
||||
"destination": "/handbook/engineering/operations/on-call-rotation"
|
||||
|
||||
Reference in New Issue
Block a user