• Product
  • Pricing
  • Docs
  • Using PostHog
  • Community
  • Company
  • Login
  • Docs

  • Overview
    • Quickstart with PostHog Cloud
    • Overview
      • AWS
      • Azure
      • DigitalOcean
      • Google Cloud Platform
      • Hobby
      • EU Hosting Companies
      • Other platforms
      • Instance settings
      • Environment variables
      • Securing PostHog
      • Monitoring with Grafana
      • Running behind a proxy
      • Configuring email
      • Helm chart configuration
      • Deploying ClickHouse using Altinity.Cloud
      • Configuring Slack
      • Overview
        • Overview
        • Upgrade notes
        • Overview
        • 0001-events-sample-by
        • 0002_events_sample_by
        • 0003_fill_person_distinct_id2
        • ClickHouse
          • Backup
          • Debug hanging / freezing process
          • Horizontal scaling (Sharding & replication)
          • Kafka Engine
          • Resize disk
          • Restore
          • Vertical scaling
        • Kafka
          • Resize disk
          • Log retention
        • PostgreSQL
          • Resize disk
          • Troubleshooting long-running migrations
        • Plugin server
        • MinIO
        • Redis
        • Zookeeper
      • Disaster recovery
    • Troubleshooting and FAQs
    • Support for self-hosting (open-source and enterprise)
    • Managing hosting costs
    • Overview
    • Ingest live data
    • Ingest historical data
    • Identify users
    • User properties
    • Deploying a reverse proxy
    • Library comparison
    • Badge
    • Browser Extensions
      • Snippet installation
      • Android
      • iOS
      • JavaScript
      • Flutter
      • React Native
      • Node.js
      • Go
      • Python
      • Rust
      • Java
      • PHP
      • Ruby
      • Elixir
      • Docusaurus v2
      • Gatsby
      • Google Tag Manager
      • Next.js
      • Nuxt.js
      • Retool
      • RudderStack
      • Segment
      • Sentry
      • Slack
      • Shopify
      • WordPress
      • Message formatting
      • Microsoft Teams
      • Slack
      • Discord
    • To another self-hosted instance
    • To PostHog from Amplitude
    • To PostHog Cloud EU
    • Between Cloud and self-hosted
    • Overview
    • Tutorial
    • Troubleshooting
    • Developer reference
    • Using the PostHog API
    • Jobs
    • Testing
    • TypeScript types
    • Overview
    • POST-only public endpoints
    • Actions
    • Annotations
    • Cohorts
    • Dashboards
    • Event definitions
    • Events
    • Experiments
    • Feature flags
    • Funnels
    • Groups
    • Groups types
    • Insights
    • Invites
    • Members
    • Persons
    • Plugin configs
    • Plugins
    • Projects
    • Property definitions
    • Session recordings
    • Trends
    • Users
    • Data model
    • Overview
    • Data model
    • Ingestion pipeline
    • ClickHouse
    • Querying data
    • Overview
    • GDPR guidance
    • HIPAA guidance
    • CCPA guidance
    • Data egress & compliance
    • Data deletion
    • Overview
    • Code of conduct
    • Recognizing contributions
  • Using PostHog

  • Table of contents
      • Dashboards
      • Funnels
      • Group Analytics
      • Insights
      • Lifecycle
      • Path analysis
      • Retention
      • Stickiness
      • Trends
      • Heatmaps
      • Session Recording
      • Correlation Analysis
      • Experimentation
      • Feature Flags
      • Actions
      • Annotations
      • Cohorts
      • Data Management
      • Events
      • Persons
      • Sessions
      • UTM segmentation
      • Team collaboration
      • Organizations & projects
      • Settings
      • SSO & SAML
      • Toolbar
      • Notifications & alerts
    • Overview
      • Amazon Kinesis Import
      • BitBucket Release Tracker
      • Event Replicator
      • GitHub Release Tracker
      • GitHub Star Sync
      • GitLab Release Tracker
      • Heartbeat
      • Ingestion Alert
      • Email Scoring
      • n8n Connector
      • Orbit Connector
      • Redshift Import
      • Segment Connector
      • Shopify Connector
      • Twitter Followers Tracker
      • Zendesk Connector
      • Airbyte Exporter
      • Amazon S3 Export
      • BigQuery Export
      • Customer.io Connector
      • Databricks Export
      • Engage Connector
      • GCP Pub/Sub Connector
      • Google Cloud Storage Export
      • Hubspot Connector
      • Intercom Connector
      • Migrator 3000
      • PagerDuty Connector
      • PostgreSQL Export
      • Redshift Export
      • RudderStack Export
      • Salesforce Connector
      • Sendgrid Connector
      • Sentry Connector
      • Snowflake Export
      • Twilio Connector
      • Variance Connector
      • Zapier Connector
      • Downsampler
      • Event Sequence Timer
      • First Time Event Tracker
      • Property Filter
      • Property Flattener
      • Schema Enforcer
      • Taxonomy Standardizer
      • Unduplicator
      • Automatic Cohort Creator
      • Currency Normalizer
      • GeoIP Enricher
      • Timestamp Parser
      • URL Normalizer
      • User Agent Populator
  • Tutorials
    • All tutorials
    • Actions
    • Apps
    • Cohorts
    • Dashboards
    • Feature flags
    • Funnels
    • Heatmaps
    • Path analysis
    • Retention
    • Session recording
    • Trends
  • Support
  • Glossary
  • Docs

  • Overview
    • Quickstart with PostHog Cloud
    • Overview
      • AWS
      • Azure
      • DigitalOcean
      • Google Cloud Platform
      • Hobby
      • EU Hosting Companies
      • Other platforms
      • Instance settings
      • Environment variables
      • Securing PostHog
      • Monitoring with Grafana
      • Running behind a proxy
      • Configuring email
      • Helm chart configuration
      • Deploying ClickHouse using Altinity.Cloud
      • Configuring Slack
      • Overview
        • Overview
        • Upgrade notes
        • Overview
        • 0001-events-sample-by
        • 0002_events_sample_by
        • 0003_fill_person_distinct_id2
        • ClickHouse
          • Backup
          • Debug hanging / freezing process
          • Horizontal scaling (Sharding & replication)
          • Kafka Engine
          • Resize disk
          • Restore
          • Vertical scaling
        • Kafka
          • Resize disk
          • Log retention
        • PostgreSQL
          • Resize disk
          • Troubleshooting long-running migrations
        • Plugin server
        • MinIO
        • Redis
        • Zookeeper
      • Disaster recovery
    • Troubleshooting and FAQs
    • Support for self-hosting (open-source and enterprise)
    • Managing hosting costs
    • Overview
    • Ingest live data
    • Ingest historical data
    • Identify users
    • User properties
    • Deploying a reverse proxy
    • Library comparison
    • Badge
    • Browser Extensions
      • Snippet installation
      • Android
      • iOS
      • JavaScript
      • Flutter
      • React Native
      • Node.js
      • Go
      • Python
      • Rust
      • Java
      • PHP
      • Ruby
      • Elixir
      • Docusaurus v2
      • Gatsby
      • Google Tag Manager
      • Next.js
      • Nuxt.js
      • Retool
      • RudderStack
      • Segment
      • Sentry
      • Slack
      • Shopify
      • WordPress
      • Message formatting
      • Microsoft Teams
      • Slack
      • Discord
    • To another self-hosted instance
    • To PostHog from Amplitude
    • To PostHog Cloud EU
    • Between Cloud and self-hosted
    • Overview
    • Tutorial
    • Troubleshooting
    • Developer reference
    • Using the PostHog API
    • Jobs
    • Testing
    • TypeScript types
    • Overview
    • POST-only public endpoints
    • Actions
    • Annotations
    • Cohorts
    • Dashboards
    • Event definitions
    • Events
    • Experiments
    • Feature flags
    • Funnels
    • Groups
    • Groups types
    • Insights
    • Invites
    • Members
    • Persons
    • Plugin configs
    • Plugins
    • Projects
    • Property definitions
    • Session recordings
    • Trends
    • Users
    • Data model
    • Overview
    • Data model
    • Ingestion pipeline
    • ClickHouse
    • Querying data
    • Overview
    • GDPR guidance
    • HIPAA guidance
    • CCPA guidance
    • Data egress & compliance
    • Data deletion
    • Overview
    • Code of conduct
    • Recognizing contributions
  • Using PostHog

  • Table of contents
      • Dashboards
      • Funnels
      • Group Analytics
      • Insights
      • Lifecycle
      • Path analysis
      • Retention
      • Stickiness
      • Trends
      • Heatmaps
      • Session Recording
      • Correlation Analysis
      • Experimentation
      • Feature Flags
      • Actions
      • Annotations
      • Cohorts
      • Data Management
      • Events
      • Persons
      • Sessions
      • UTM segmentation
      • Team collaboration
      • Organizations & projects
      • Settings
      • SSO & SAML
      • Toolbar
      • Notifications & alerts
    • Overview
      • Amazon Kinesis Import
      • BitBucket Release Tracker
      • Event Replicator
      • GitHub Release Tracker
      • GitHub Star Sync
      • GitLab Release Tracker
      • Heartbeat
      • Ingestion Alert
      • Email Scoring
      • n8n Connector
      • Orbit Connector
      • Redshift Import
      • Segment Connector
      • Shopify Connector
      • Twitter Followers Tracker
      • Zendesk Connector
      • Airbyte Exporter
      • Amazon S3 Export
      • BigQuery Export
      • Customer.io Connector
      • Databricks Export
      • Engage Connector
      • GCP Pub/Sub Connector
      • Google Cloud Storage Export
      • Hubspot Connector
      • Intercom Connector
      • Migrator 3000
      • PagerDuty Connector
      • PostgreSQL Export
      • Redshift Export
      • RudderStack Export
      • Salesforce Connector
      • Sendgrid Connector
      • Sentry Connector
      • Snowflake Export
      • Twilio Connector
      • Variance Connector
      • Zapier Connector
      • Downsampler
      • Event Sequence Timer
      • First Time Event Tracker
      • Property Filter
      • Property Flattener
      • Schema Enforcer
      • Taxonomy Standardizer
      • Unduplicator
      • Automatic Cohort Creator
      • Currency Normalizer
      • GeoIP Enricher
      • Timestamp Parser
      • URL Normalizer
      • User Agent Populator
  • Tutorials
    • All tutorials
    • Actions
    • Apps
    • Cohorts
    • Dashboards
    • Feature flags
    • Funnels
    • Heatmaps
    • Path analysis
    • Retention
    • Session recording
    • Trends
  • Support
  • Glossary
  • Docs
  • Integrate PostHog
  • Client libraries
  • iOS

iOS

Last updated: Oct 13, 2022

On this page

  • Installation
  • Configuration
  • Making calls
  • Identify
  • Capture
  • Setting user properties via an event
  • $set
  • $set_once
  • Flush
  • Reset
  • Sending screen views
  • A note about IDFA (identifier for advertisers) collection in iOS 14
  • Group analytics
  • Feature Flags
  • All configuration options
  • Thank you
Which features are available in this library?
  • AvailableEvent capture
  • Not availableAutocapture
  • AvailableUser identification
  • Not availableSession recording
  • AvailableFeature flags
  • AvailableGroup 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: "1.4.4")
],

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>
// on posthog.com
PHGPostHogConfiguration *configuration = [PHGPostHogConfiguration configurationWithApiKey:@"YOUR_API_KEY"];
// self-hosted
PHGPostHogConfiguration *configuration = [PHGPostHogConfiguration configurationWithApiKey:@"YOUR_API_KEY"
host:@"https://app.posthog.com"];
configuration.captureApplicationLifecycleEvents = YES; // Record certain application events automatically!
configuration.recordScreenViews = YES; // Record screen views automatically!
[PHGPostHog setupWithConfiguration:configuration];

With Swift

Swift
import PostHog
// `host` is optional if you use PostHog Cloud (app.posthog.com)
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()

Making calls

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.

Capture

Capture allows you to send events related to anything a user does within your system, which you can later use in PostHog to find patterns in usage, work out which features to improve, or find out where people are giving up.

A capture call requires:

  • event name to specify the event
    • We recommend using [noun][verb], like movie played or movie updated to easily identify what your events mean later on.

Optionally you can submit:

  • properties, which can be an array with any information you'd like to add

For example:

Objective-C
// in objective-c
[[PHGPostHog sharedPostHog] capture:@"Signed Up" properties:@{ @"plan": @"Pro++" }];
Swift
// in swift
posthog.capture("Signed Up", properties: ["plan": "Pro++"])

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

Sending 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.capture("Dashboard", properties: ["fromIcon": "bottom"])

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.

Group analytics

PostHog 1.31.0 introduced support for group analytics, which allows you to associate users and events with larger groups (teams, organizations, etc.). This feature requires a posthog-node version of 1.2.0 or above.

Note: This is a paid feature and is not available on the open-source or free cloud plan. Learn more here.

  • Capture an event and associate it with a group
Objective-C
[[PHGPostHog sharedPostHog] group:@"some-type" groupKey:@"some-key" properties:@{ @"name": @"some-company-name" }];
Swift
posthog.group( "some-type", groupKey: "some-key", properties: [
"name": "some-company-name"
])

Feature Flags

PostHog v1.10.0 introduced Feature Flags, which allow you to safely deploy and roll back new features.

Here's how you can use them:

  • Check if a feature is enabled:
Objective-C
[[PHGPosthog sharedPostHog] isFeatureEnabled:@"keyword"];
Swift
posthog.isFeatureEnabled('keyword')
  • Trigger a reload of the feature flags:
Objective-C
[[PHGPosthog sharedPostHog] reloadFeatureFlags];
Swift
posthog.reloadFeatureFlags()
  • By default, this function will send a $feature_flag_called event to your instance every time it's called so you're able to do analytics.

Get a flag value

If you're using multivariate feature flags, you can also get the value of the flag, as well as whether or not it is enabled.

Objective-C
[[PHGPosthog sharedPostHog] getFeatureFlag:@"some-flag"];
Swift
posthog.getFeatureFlag("some-flag")

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

JavaScript

Note: You can just use our snippet to start capturing events with our JS. This page of the Docs refers to our posthog-js library. Why does this exist? The reason this exists is that whilst the default snippet captures every click on certain elements (like a , button , input etc.) and page views, it's often worth sending more context whenever a user does something. This might also be useful if you have a one page app. Installation Usage Autocapture Important notes on autocapture While…

Read next article

Authors

  • Li Yi Yu
    Li Yi Yu
  • Paul Hultgren
    Paul Hultgren
  • Eli Kinsey
    Eli Kinsey

Share

Jump to:

  • Installation
  • Configuration
  • Making calls
  • Identify
  • Capture
  • Flush
  • Reset
  • Sending screen views
  • A note about IDFA (identifier for advertisers) collection in iOS 14
  • Group analytics
  • Feature Flags
  • All configuration options
  • Thank you
  • Questions?
  • Edit this page
  • Raise an issue
  • Toggle content width
  • Toggle dark mode
  • Product

  • Overview
  • Pricing
  • Product analytics
  • Session recording
  • A/B testing
  • Feature flags
  • Apps
  • Customer stories
  • PostHog vs...
  • Docs

  • Quickstart guide
  • Self-hosting
  • Installing PostHog
  • Building an app
  • API
  • Webhooks
  • How PostHog works
  • Data privacy
  • Using PostHog

  • Product manual
  • Apps manuals
  • Tutorials
  • Community

  • Questions?
  • Product roadmap
  • Contributors
  • Partners
  • Newsletter
  • Merch
  • PostHog FM
  • PostHog on GitHub
  • Handbook

  • Getting started
  • Company
  • Strategy
  • How we work
  • Small teams
  • People & Ops
  • Engineering
  • Product
  • Design
  • Marketing
  • Customer success
  • Company

  • About
  • Team
  • Investors
  • Press
  • Blog
  • FAQ
  • Support
  • Careers
© 2022 PostHog, Inc.
  • Code of conduct
  • Privacy policy
  • Terms