iOS

Last updated:

|Edit this page
Which features are available in this library?
  • Event capture
  • Autocapture
  • User identification
  • Session recording
  • Feature flags
  • Group analytics

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.

PostHog supports the Apple platforms: iOS, macOS, tvOS and watchOS.

Installation

PostHog is available through CocoaPods or you can add it as a Swift Package Manager based dependency.

CocoaPods

Podfile
pod "PostHog", "~> 3.0.0"

Swift Package Manager

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:

Package.swift
dependencies: [
.package(url: "https://github.com/PostHog/posthog-ios.git", from: "3.0.0")
],

and then as a dependency for the Package target utilizing PostHog:

Swift
.target(
name: "myApp",
dependencies: [.product(name: "PostHog", package: "posthog-ios")]),

Configuration

Swift
import Foundation
import PostHog
import UIKit
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
let POSTHOG_API_KEY = "<ph_project_api_key>"
// usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com'
let POSTHOG_HOST = "<ph_client_api_host>"
let config = PostHogConfig(apiKey: POSTHOG_API_KEY, host: POSTHOG_HOST)
PostHogSDK.shared.setup(config)
return true
}
}

Capturing events

You can send custom events using capture:

Swift
PostHogSDK.shared.capture("user_signed_up")

Tip: We recommend using a '[object][verb]' format for your event names, where '[object]' is the entity that the behavior relates to, and '[verb]' is the behavior itself. For example, project created, user signed up, or invite sent.

Setting event properties

Optionally, you can also include additional information in the event by setting the properties value:

Swift
PostHogSDK.shared.capture("user_signed_up", properties: ["login_type": "email"], userProperties: ["is_free_trial": true])

Autocapture

PostHog autocapture automatically tracks the following events for you:

  • Application Opened - when the app is opened from a closed state or when the app comes to the foreground (e.g. from the app switcher)
  • Deep Link Opened - when the app is opened from a deep link.
  • Application Backgrounded - when the app is sent to the background by the user
  • Application Installed - when the app is installed.
  • Application Updated - when the app is updated.
  • $screen - when the user navigates (if using UIViewController)

Capturing screen views

With configuration.captureScreenViews 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.

Swift
PostHogSDK.shared.screen("Dashboard", properties: ["fromIcon": "bottom"])

Identifying users

We highly recommend reading our section on Identifying users to better understand how to correctly use this method.

Using identify, you can associate events with specific users. This enables you to gain full insights as to how they're using your product across different sessions, devices, and platforms.

An identify call has the following arguments:

  • distinct_id which uniquely identifies your user in your database
Swift
PostHogSDK.shared.identify("user_id_from_your_database",
userProperties: ["name": "Peter Griffin", "email": "peter@familyguy.com"],
userPropertiesSetOnce: ["date_of_first_log_in": "2024-03-01"])

You should call identify as soon as you're able to. Typically, this is every time your app loads for the first time as well as directly after your user logs in. This ensures that events sent during your user's sessions are correctly associated with them.

When you call identify, all previously tracked anonymous events will be linked to the user.

Alias

Sometimes, you may want to assign multiple distinct IDs to a single user. This is helpful in scenarios where your primary distinct ID may be inaccessible. For example, if a distinct ID which is typically used on the frontend is not available in certain parts of your backend code. In this case, you can use alias to assign another distinct ID to the same user.

We strongly recommend reading our docs on alias to best understand how to correctly use this method.

Setting user properties

To set properties on your users via an event, you can leverage the event properties userProperties and userPropertiesSetOnce.

userProperties

Example

Swift
PostHogSDK.shared.capture("signed_up", properties: ["plan": "Pro++"], userProperties: ["user_property_name": "your_value"])

Usage

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.

userPropertiesSetOnce

Example

Swift
PostHogSDK.shared.capture("signed_up", properties: ["plan": "Pro++"], userPropertiesSetOnce: ["user_property_name": "your_value"])

Usage

userPropertiesSetOnce works just like userProperties, except that it will only set the property if the user doesn't already have that property set.

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.

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.

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()

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 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.

  • 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

PostHog's feature flags enable you to safely deploy and roll back new features.

Boolean feature flags

Swift
if (PostHogSDK.shared.isFeatureEnabled("flag-key")) {
// Do something differently for this user
// Optional: fetch the payload
let matchedFlagPayload = PostHogSDK.shared.getFeatureFlagPayload("flag-key")
}

Multivariate feature flags

Swift
if (PostHogSDK.shared.getFeatureFlag("flag-key") as? String == "variant-key") { // replace "variant-key" with the key of your variant
// Do something differently for this user
// Optional: fetch the payload
let matchedFlagPayload = PostHogSDK.shared.getFeatureFlagPayload("flag-key")
}

Ensuring flags are loaded before usage

Every time a user loads a screen, we send a request in the background to fetch the feature flags that apply to that user. We store those flags in the storage.

This means that for most screens, the feature flags are available immediately – except for the first time a user visits.

To handle this, you can use the didReceiveFeatureFlags notification to wait for the feature flag request to finish:

Swift
// Before SDK initialization
NotificationCenter.default.addObserver(self, selector: #selector(receiveFeatureFlags), name: PostHogSDK.didReceiveFeatureFlags, object: nil)
PostHogSDK.shared.setup(config)
// The "receiveFeatureFlags" method will be called when the SDK receives the feature flags from the server.
// And/Or manually the SDK is initialized
PostHogSDK.shared.reloadFeatureFlags {
if PostHogSDK.shared.isFeatureEnabled("flag-key") {
// do something
}
}

Reloading feature flags

Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call:

Swift
PostHogSDK.shared.reloadFeatureFlags()

Experiments (A/B tests)

Since experiments 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.

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 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.

All configuration 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
/**
* 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
/**
* 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

Questions?

Was this page useful?

Next article

Java

This is an optional library you can install if you're working with Java. It 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 web app or other server side application that needs performance. Installation Capturing events Setting user properties To set user properties , include the properties you'd like to set when capturing an event: For more details on the difference between $set and…

Read next article