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.

Installation

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

CocoaPods

Podfile
pod "PostHog", "~> 1.1"

Carthage

Cartfile
github "posthog/posthog-ios"

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: "2.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

With Objective-C

Objective-C
#import <PostHog/PHGPostHog.h>
#import <PostHog/PHGPostHogConfiguration.h>
// cloud-hosted
PHGPostHogConfiguration *configuration = [PHGPostHogConfiguration configurationWithApiKey:@"<ph_project_api_key>"];
// self-hosted
PHGPostHogConfiguration *configuration = [PHGPostHogConfiguration configurationWithApiKey:@"<ph_project_api_key>"
host:@"https://your-posthog-domain.com"];
configuration.captureApplicationLifecycleEvents = YES; // Record certain application events automatically!
configuration.recordScreenViews = YES; // Record screen views automatically!
[PHGPostHog setupWithConfiguration:configuration];

With Swift

Swift
import PostHog
let configuration = PHGPostHogConfiguration(apiKey: "<ph_project_api_key>", host: "<ph_instance_address>")
configuration.captureApplicationLifecycleEvents = true; // Record certain application events automatically!
configuration.recordScreenViews = true; // Record screen views automatically!
PHGPostHog.setup(with: configuration)
let posthog = PHGPostHog.shared()

Capturing events

You can send custom events using capture:

Objective-C
[[PHGPostHog sharedPostHog] capture:@"user signed up"];
Swift
posthog.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:

Objective-C
[[PHGPostHog sharedPostHog] capture:@"user signed up"
properties:@{ @"login_type": @"email",
@"$is_free_trial": @YES }
];
Swift
posthog.capture(
"user signed up",
properties: ["login_type": "email", "$set": ["is_free_trial": true]
])

Capturing screen views

With configuration.recordScreenViews set as YES, PostHog will try to record all screen changes automatically.

If you want to manually send a new screen capture event, use the screen function.

Objective-C
[[PHGPostHog sharedPostHog] screen:@"Dashboard" properties:@{ @"fromIcon": @"bottom" }];
Swift
posthog.screen("Dashboard", properties: ["fromIcon": "bottom"])

Identify

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

When you start tracking events with PostHog, each user gets an anonymous ID that is used to identify them in the system. In order to link this anonymous user with someone from your database, use the identify call.

Identify lets you add metadata to your users so you can easily identify who they are in PostHog, as well as do things like segment users by these properties.

An identify call requires:

  • distinct_id which uniquely identifies your user in your database
  • properties with a dictionary of key:value pairs

For example:

Objective-C
// in objective-c
[[PHGPostHog sharedPostHog] identify:@"distinct_id_from_your_database"
properties:@{ @"name": @"Peter Griffin",
@"email": @"peter@familyguy.com" }];
Swift
// in swift
posthog.identify("user_id_from_your_database",
properties: ["name": "Peter Griffin", "email": "peter@familyguy.com"])

The most obvious place to make this call is whenever a user signs up, or when they update their information.

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

Setting user properties via an event

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

$set

Example

Objective-C
[[PHGPostHog sharedPostHog] capture:@"Signed Up" properties:@{ @"plan": @"Pro++", @"$set":@{ @"userProp": "value1" } }];
Swift
posthog.capture("Signed Up", properties: ["plan": "Pro++", "$set": ["userProp": "value1"] ])

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.

$set_once

Example

Objective-C
[[PHGPostHog sharedPostHog] capture:@"Signed Up" properties:@{ @"plan": @"Pro++", @"$set_once":@{ @"userProp": "value1" } }];
Swift
posthog.capture("Signed Up", properties: ["plan": "Pro++", "$set_once": ["userProp": "value1"] ])

Usage

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

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.

Objective-C
configuration.flushAt = 1;

You can also manually flush the queue:

Objective-C
[[PHGPostHog sharedPostHog] capture:@"Logged Out"];
[[PHGPostHog sharedPostHog] flush]
Swift
posthog.capture('Logged Out')
posthog.flush()

Reset

To reset the user's ID and anonymous ID, call reset. Usually you would do this right after the user logs out.

Objective-C
[[PHGPostHog sharedPostHog] reset]
Swift
posthog.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
Objective-C
[[PHGPostHog sharedPostHog] group:@"company" groupKey:@"company_id_in_your_db"];
Swift
posthog.group( "company", groupKey: "company_id_in_your_db")
  • Associate the events for this session with a group AND update the properties of that group
Objective-C
[[PHGPostHog sharedPostHog] group:@"company" groupKey:@"company_id_in_your_db" properties:@{ @"name": @"Awesome Inc." }];
Swift
posthog.group( "company", groupKey: "company_id_in_your_db", properties: [
"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 (posthog.isFeatureEnabled('flag-key')) {
// Do something differently for this user
}

Multivariate feature flags

Swift
if (posthog.getFeatureFlag('my-flag') == "variant-key") { // replace 'variant-key' with the key of your variant
// do something
}

Reloading feature flags

Feature flag values are cached. If something has change with your user and you'd like to refetch their flag values, call posthog.reloadFeatureFlags().

Experiments (A/B tests)

Since experiments use feature flags, the code for running an experiment is very similar to the feature flags code:

Objective-C
if ([[PHGPosthog sharedPostHog] getFeatureFlag:@"experiment-feature-flag-key"] == @"variant-name") {
// do something
}
Swift
if (posthog.getFeatureFlag('experiment-feature-flag-key') == '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:

Objective-C
/**
* Whether the posthog client should use location services.
* If `YES` and the host app hasn't asked for permission to use location services then the user will be
* presented with an alert view asking to do so. `NO` by default. If `YES`, please make sure to add a
* description for `NSLocationAlwaysUsageDescription` in your `Info.plist` explaining why your app is
* accessing Location APIs.
*/
configuration.shouldUseLocationServices = NO;
/**
* 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.flushInterval = 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;
/**
* Whether the posthog client should automatically make a capture call for application lifecycle events,
* such as "Application Installed", "Application Updated" and "Application Opened".
*/
configuration.captureApplicationLifecycleEvents = NO;
/**
* Whether the posthog client should record bluetooth information. If `YES`, please make sure to add a
* description for `NSBluetoothPeripheralUsageDescription` in your `Info.plist` explaining explaining why
* your app is accessing Bluetooth APIs. `NO` by default.
*/
configuration.shouldUseBluetooth = NO;
/**
* 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.
*/
configuration.recordScreenViews = NO;
/**
* Whether the posthog client should automatically capture in-app purchases from the App Store.
*/
configuration.captureInAppPurchases = NO;
/**
* Whether the posthog client should automatically capture push notifications.
*/
configuration.capturePushNotifications = NO;
/**
* Whether the posthog client should automatically capture deep links. You'll still need to call the
* continueUserActivity and openURL methods on the posthog client.
*/
configuration.captureDeepLinks = NO;
/**
* Whether the posthog client should include the `$device_id` property when sending events.
* When enabled, `UIDevice`'s `identifierForVendor` property is used. Changing the value of
* of this property after initializing the client will have no effect.
* The default value is `YES`.
*/
configuration.shouldSendDeviceID = YES;

Thank you

This library is largely based on the analytics-ios package.

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