Documentation

Developers

API References
Data Subject Request API

Data Subject Request API Version 1 and 2

Data Subject Request API Version 3

Platform API

Platform API Overview

Accounts

Apps

Audiences

Calculated Attributes

Data Points

Feeds

Field Transformations

Services

Users

Workspaces

Warehouse Sync API

Warehouse Sync API Overview

Warehouse Sync API Tutorial

Warehouse Sync API Reference

Data Mapping

Warehouse Sync SQL Reference

Warehouse Sync Troubleshooting Guide

ComposeID

Warehouse Sync API v2 Migration

Bulk Profile Deletion API Reference

Calculated Attributes Seeding API

Custom Access Roles API

Data Planning API

Group Identity API Reference

Pixel Service

Profile API

Events API

mParticle JSON Schema Reference

IDSync

Client SDKs
AMP

AMP SDK

Android

Initialization

Configuration

Network Security Configuration

Event Tracking

User Attributes

IDSync

Screen Events

Commerce Events

Location Tracking

Media

Kits

Application State and Session Management

Data Privacy Controls

Error Tracking

Opt Out

Push Notifications

WebView Integration

Logger

Preventing Blocked HTTP Traffic with CNAME

Linting Data Plans

Troubleshooting the Android SDK

API Reference

Upgrade to Version 5

Direct Url Routing

Direct URL Routing FAQ

Web

Android

iOS

Cordova

Cordova Plugin

Identity

iOS

Initialization

Configuration

Event Tracking

User Attributes

IDSync

Screen Tracking

Commerce Events

Location Tracking

Media

Kits

Application State and Session Management

Data Privacy Controls

Error Tracking

Opt Out

Push Notifications

Webview Integration

Upload Frequency

App Extensions

Preventing Blocked HTTP Traffic with CNAME

Linting Data Plans

Troubleshooting iOS SDK

Social Networks

iOS 14 Guide

iOS 15 FAQ

iOS 16 FAQ

iOS 17 FAQ

iOS 18 FAQ

API Reference

Upgrade to Version 7

Flutter

Getting Started

Usage

API Reference

React Native

Getting Started

Identity

Roku

Getting Started

Identity

Media

Xbox

Getting Started

Identity

Unity

Upload Frequency

Getting Started

Opt Out

Initialize the SDK

Event Tracking

Commerce Tracking

Error Tracking

Screen Tracking

Identity

Location Tracking

Session Management

Xamarin

Getting Started

Identity

Web

Initialization

Configuration

Content Security Policy

Event Tracking

User Attributes

IDSync

Page View Tracking

Commerce Events

Location Tracking

Media

Kits

Application State and Session Management

Data Privacy Controls

Error Tracking

Opt Out

Custom Logger

Persistence

Native Web Views

Self-Hosting

Multiple Instances

Web SDK via Google Tag Manager

Preventing Blocked HTTP Traffic with CNAME

Facebook Instant Articles

Troubleshooting the Web SDK

Browser Compatibility

Linting Data Plans

API Reference

Upgrade to Version 2 of the SDK

Web

Alexa

Media SDKs

Android

iOS

Web

Quickstart
Android

Overview

Step 1. Create an input

Step 2. Verify your input

Step 3. Set up your output

Step 4. Create a connection

Step 5. Verify your connection

Step 6. Track events

Step 7. Track user data

Step 8. Create a data plan

Step 9. Test your local app

HTTP Quick Start

Step 1. Create an input

Step 2. Create an output

Step 3. Verify output

iOS Quick Start

Overview

Step 1. Create an input

Step 2. Verify your input

Step 3. Set up your output

Step 4. Create a connection

Step 5. Verify your connection

Step 6. Track events

Step 7. Track user data

Step 8. Create a data plan

Java Quick Start

Step 1. Create an input

Step 2. Create an output

Step 3. Verify output

Node Quick Start

Step 1. Create an input

Step 2. Create an output

Step 3. Verify output

Python Quick Start

Step 1. Create an input

Step 2. Create an output

Step 3. Verify output

Web

Overview

Step 1. Create an input

Step 2. Verify your input

Step 3. Set up your output

Step 4. Create a connection

Step 5. Verify your connection

Step 6. Track events

Step 7. Track user data

Step 8. Create a data plan

Server SDKs

Node SDK

Go SDK

Python SDK

Ruby SDK

Java SDK

Tools

Linting Tools

Smartype

mParticle Command Line Interface

Guides
Partners

Introduction

Outbound Integrations

Outbound Integrations

Firehose Java SDK

Inbound Integrations

Kit Integrations

Overview

Android Kit Integration

JavaScript Kit Integration

iOS Kit Integration

Compose ID

Data Hosting Locations

Glossary

Migrate from Segment to mParticle

Migrate from Segment to mParticle

Migrate from Segment to Client-side mParticle

Migrate from Segment to Server-side mParticle

Segment-to-mParticle Migration Reference

Rules Developer Guide

API Credential Management

The Developer's Guided Journey to mParticle

Guides

Getting Started

Create an Input

Start capturing data

Connect an Event Output

Create an Audience

Connect an Audience Output

Transform and Enhance Your Data

Platform Guide
The New mParticle Experience

The new mParticle Experience

The Overview Map

Observability

Observability Overview

Observability User Guide

Observability Span Glossary

Introduction

Data Retention

Connections

Activity

Live Stream

Data Filter

Rules

Tiered Events

mParticle Users and Roles

Analytics Free Trial

Troubleshooting mParticle

Usage metering for value-based pricing (VBP)

Analytics

Introduction

Setup

Sync and Activate Analytics User Segments in mParticle

User Segment Activation

Welcome Page Announcements

Settings

Project Settings

Roles and Teammates

Organization Settings

Global Project Filters

Portfolio Analytics

Analytics Data Manager

Analytics Data Manager Overview

Events

Event Properties

User Properties

Revenue Mapping

Export Data

UTM Guide

Query Builder

Data Dictionary

Query Builder Overview

Modify Filters With And/Or Clauses

Query-time Sampling

Query Notes

Filter Where Clauses

Event vs. User Properties

Group By Clauses

Annotations

Cross-tool Compatibility

Apply All for Filter Where Clauses

Date Range and Time Settings Overview

Understanding the Screen View Event

Analyses

Analyses Introduction

Segmentation: Basics

Getting Started

Visualization Options

For Clauses

Date Range and Time Settings

Calculator

Numerical Settings

Segmentation: Advanced

Assisted Analysis

Properties Explorer

Frequency in Segmentation

Trends in Segmentation

Did [not] Perform Clauses

Cumulative vs. Non-Cumulative Analysis in Segmentation

Total Count of vs. Users Who Performed

Save Your Segmentation Analysis

Export Results in Segmentation

Explore Users from Segmentation

Funnels: Basics

Getting Started with Funnels

Group By Settings

Conversion Window

Tracking Properties

Date Range and Time Settings

Visualization Options

Interpreting a Funnel Analysis

Funnels: Advanced

Group By

Filters

Conversion over Time

Conversion Order

Trends

Funnel Direction

Multi-path Funnels

Analyze as Cohort from Funnel

Save a Funnel Analysis

Explore Users from a Funnel

Export Results from a Funnel

Cohorts

Getting Started with Cohorts

Analysis Modes

Save a Cohort Analysis

Export Results

Explore Users

Saved Analyses

Manage Analyses in Dashboards

Users

Getting Started

User Activity Timelines

Time Settings

Export Results

Save A User Analysis

Journeys

Getting Started

Event Menu

Visualization

Ending Event

Save a Journey Analysis

Dashboards

Dashboards––Getting Started

Manage Dashboards

Organize Dashboards

Dashboard Filters

Scheduled Reports

Favorites

Time and Interval Settings in Dashboards

Query Notes in Dashboards

User Aliasing

Analytics Resources

The Demo Environment

Keyboard Shortcuts

Tutorials

Analytics for Marketers

Analytics for Product Managers

Compare Conversion Across Acquisition Sources

Analyze Product Feature Usage

Identify Points of User Friction

Time-based Subscription Analysis

Dashboard Tips and Tricks

Understand Product Stickiness

Optimize User Flow with A/B Testing

User Segments

APIs

User Segments Export API

Dashboard Filter API

IDSync

IDSync Overview

Use Cases for IDSync

Components of IDSync

Store and Organize User Data

Identify Users

Default IDSync Configuration

Profile Conversion Strategy

Profile Link Strategy

Profile Isolation Strategy

Best Match Strategy

Aliasing

Data Master
Group Identity

Overview

Create and Manage Group Definitions

Introduction

Catalog

Live Stream

Data Plans

Data Plans

Blocked Data Backfill Guide

Personalization
Predictive Audiences

Predictive Audiences Overview

Using Predictive Audiences

Predictive Attributes

Predictive Attributes Overview

Create Predictive Attributes

Assess and Troubleshoot Predictions

Use Predictive Attributes in Campaigns

Introduction

Profiles

Calculated Attributes

Calculated Attributes Overview

Using Calculated Attributes

Create with AI Assistance

Calculated Attributes Reference

Audiences

Audiences Overview

Real-time Audiences

Standard Audiences

Journeys

Journeys Overview

Manage Journeys

Download an audience from a journey

Audience A/B testing from a journey

Journeys 2.0

Warehouse Sync

Data Privacy Controls

Data Subject Requests

Default Service Limits

Feeds

Cross-Account Audience Sharing

Approved Sub-Processors

Import Data with CSV Files

Import Data with CSV Files

CSV File Reference

Glossary

Video Index

Analytics (Deprecated)
Settings

Debug Console

Data Warehouse Delay Alerting

Identity Providers

Single Sign-On (SSO)

Setup Examples

Introduction

Developer Docs

Introduction

Integrations

Introduction

Rudderstack

Google Tag Manager

Segment

Data Warehouses and Data Lakes

Advanced Data Warehouse Settings

AWS Kinesis (Snowplow)

AWS Redshift (Define Your Own Schema)

AWS S3 Integration (Define Your Own Schema)

AWS S3 (Snowplow Schema)

BigQuery (Snowplow Schema)

BigQuery Firebase Schema

BigQuery (Define Your Own Schema)

GCP BigQuery Export

Snowplow Schema Overview

Snowflake (Snowplow Schema)

Snowflake (Define Your Own Schema)

APIs

Dashboard Filter API (Deprecated)

REST API

User Segments Export API (Deprecated)

SDKs

SDKs Introduction

React Native

iOS

Android

Java

JavaScript

Python

Object API

Developer Basics

Aliasing

IDSync

The SDK surfaces a series of APIs allowing you to manage user-identity state. These client-side APIs work in tandem with the mParticle IDSync HTTP API and your configured “identity strategy.” These APIs are designed generically but identity management requirements vary by app - so it’s crucial that you use the APIs correctly per your requirements.

See the mParticle IDSync overview for a platform-agnostic overview of the key operations you can perform and read below for how the API is surfaced for iOS.

Overview

There are four key APIs exposed via the iOS SDK:

  • “identify”
  • “login”
  • “logout”
  • “modify”

The following applies to all of these APIs:

  • All APIs are asynchronous
  • All APIs accept the same MPIdentityApiRequest object type
  • All APIs accept a completion block which will be invoked for success and failure
  • All APIs follow the same user-transition paradigm: the identity request dictates the details of the user you would like to transition the SDK to, not the user you are transitioning from. The SDK maintains a “current” user, to which all events are attributed until the current user changes.
  • Every time they are invoked, the SDK will immediately upload an HTTP request. Because of this, these APIs must only be invoked when the user actually logs in, logs out, or otherwise changes state. A common mistake is to call an API such as identify or login on every app startup or page load - this is not necessary and will result in high network traffic.

Creating an IDSync Request

Populating IDSync requests correctly is crucial to managing the state of your users and the association of events.

An MPIdentityApiRequest is a holder for a set of identities that you would like to associate with the user. The MPIdentityApiRequest provides two helper class methods:

  • [MPIdentityApiRequest requestWithEmptyUser] - this will result in an empty user/request
  • [MPIdentityApiRequest requestWithUser:currentUser] - this will result in a request containing the same identities as the given user, which you can then mutate further
MPIdentityApiRequest *identityRequest = [MPIdentityApiRequest requestWithEmptyUser];
//the MPIdentityApiRequest provides convenience methods for common identity types
identityRequest.email = @"foo@example.com";
identityRequest.customerId = @"123456";
//alternatively, you can use the setIdentity method and supply the MPIdentity type
[identityRequest setIdentity: [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString] identityType:MPIdentityIOSAdvertiserId];
[identityRequest setIdentity: @"bar-id" identityType:MPIdentityOther];
let identityRequest = MPIdentityApiRequest.withEmptyUser()
//the MPIdentityApiRequest provides convenience methods for common identity types
identityRequest.email = "foo@example.com"
identityRequest.customerId = "123456"
//alternatively, you can use the setIdentity method and supply the MPIdentity type
identityRequest.setIdentity("bar-id", identityType: MPIdentity.other)
identityRequest.setIdentity(ASIdentifierManager.shared().advertisingIdentifier.uuidString, identityType: MPIdentity.iosAdvertiserId)

When you invoke any of the four key IDSync APIs with an MPIdentityApiRequest:

  • The SDK will verify the contents of the API request, resulting in a potential runtime warning or error
  • The SDK will automatically append device identities such as the iOS Advertising ID (IDFA) to the IDSync request
  • The SDK will invoke the requested IDSync operation with all of the supplied identities
  • The IDSync HTTP API will respond with a matching MPID. The SDK will automatically switch to this MPID and all future events will be associated with that MPID.

SDK Initialization and Identify

The “identify” API is unique in that it is called automatically on SDK initialization by the mParticle SDK. The SDK requires this call to succeed in order to establish an mParticle ID to associate with all data.

There are several considerations to account for during SDK initialization:

  • If the user is already logged in during initialization of your app (from a previous session), or you otherwise have identifying information about the user that you would like to supply, you should create an MPIdentityApiRequest and set it to the identify field of your MParticleOptions object, and supply that to mParticle’s start API. See the SDK initialization example below.
  • If you do not provide an MPIdentityApiRequest during SDK initialization, the mParticle SDK will use its local persistence to generate an MPIdentityApiRequest for you based off of the most recent user, supplying the most recent user identities.
  • If this is a new app-install, and the identify call fails, you should retry the request. See below for information on reacting to failed IDSync API requests.

Here’s an example of how you might initialize the SDK and set a user-attribute once the user object becomes available:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //initialize mParticle
    MParticleOptions *options = [MParticleOptions optionsWithKey:@"REPLACE WITH APP KEY"
                                                      secret:@"REPLACE WITH APP SECRET"];
    MPIdentityApiRequest *identityRequest = [MPIdentityApiRequest requestWithEmptyUser];
    identityRequest.email = @"foo@example.com";
    identityRequest.customerId = @"123456";
    options.identifyRequest = identityRequest;
    options.onIdentifyComplete = ^(MPIdentityApiResult *_Nullable apiResult, NSError *_Nullable error) {
        if (apiResult) {
            [apiResult.user setUserAttribute:@"example attribute key"
                                       value:@"example attribute value"];
        } else {
            //handle failure - see below
        }
    };
    [[MParticle sharedInstance] startWithOptions:options];
    return YES;
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    let options = MParticleOptions(key: "REPLACE WITH APP KEY",
                                secret: "REPLACE WITH APP SECRET")
    let identityRequest = MPIdentityApiRequest.withEmptyUser()
    identityRequest.email = "foo@example.com"
    identityRequest.customerId = "123456"
    options.identifyRequest = identityRequest
    options.onIdentifyComplete =  {(result: MPIdentityApiResult?, error: Error?) in
        if let user = result?.user {
            user.setUserAttribute("example attribute key", value: "example attribute value")
        } else {
            //handle failure - see "Error Handling" section below
        }
    }

    MParticle.sharedInstance().start(with: options)
}

Login and Logout

The login and logout APIs should be invoked at the time of the user performing the matching actions in your application. These methods have identical signatures - they accept an MPIdentityApiRequest and a completion handler which will be invoked with either a successful MPIdentityApiResult or an NSError:

// Define your identityRequest
MPIdentityApiRequest *identityRequest = [MPIdentityApiRequest requestWithEmptyUser];
// Include any identities you want to associate with the logged in user here. 
// See "Creating an IDSync request" above for more details.
// This example shows the addition of the email identity.
identityRequest.email = @"foo@example.com";

// Call the login method, passing in the identityRequest you just created
[[[MParticle sharedInstance] identity] login:identityRequest completion:identityCallback];
// Define your identityRequest
let identityRequest = MPIdentityApiRequest.withEmptyUser()
// Include any identities you want to associate with the logged in user here. 
// See "Creating an IDSync request" above for more details.
// This example shows the addition of the email identity.
identityRequest.email = "foo@example.com"

// Call the login method, passing in the identityRequest you just created
MParticle.sharedInstance().identity.login(identityRequest, completion: identityCallback)

Logout is invoked similarly to login, and you can supply an MPIdentityApiRequest if you have anonymous identifiers you would like to associate with the logged-out user state. More commonly, you can exclude the IdentityApiRequest to denote that the logged-out user should have no associated user identities: —>

[[[MParticle sharedInstance] identity] logoutWithCompletion:identityCallback];

// exluding the identity request from any IDSync API is the same as invoking the following:
[[[MParticle sharedInstance] identity] logout:[MPIdentityApiRequest requestWithEmptyUser]
                                   completion:identityCallback];
MParticle.sharedInstance().identity.logout(completion: identityCallback)

// exluding the identity request from any IDSync API is the same as invoking the following:
MParticle.sharedInstance().identity.logout(MPIdentityApiRequest.withEmptyUser(),
                                            completion: identityCallback)

Modify

Modify also has the identical signature, but note a crucial difference: modify actions are always for a specific mParticle ID (MPID) - they will never result in a new user or MPID. Modify can only add, remove, or change the identities associated with an existing user. Please note that this should not be used to handle registration/login and logout scenarios. Modify is generally used when a user updates their profile in their app, such as updating their email.

For each modify request:

  • the SDK will assign the current user’s mParticle ID (MPID) to the request if you did not supply a user while creating the request object
  • the SDK will calculate a delta between the given MPID’s known user identities, stored on the current device, with those that you supply within the MPIdentityApiRequest, and invoke the underlying IDSync HTTP API

In this example, the SDK will change the email of the current user, or add the email to the user’s profile if the user has no existing email on this device:

MPIdentityApiRequest *identityRequest = [MPIdentityApiRequest requestWithEmptyUser];
identityRequest.email = @"updated-email@example.com";
[[[MParticle sharedInstance] identity] modify:identityRequest completion:identityCallback];
var identityRequest = MPIdentityApiRequest.withEmptyUser()
identityRequest.email = "updated-email@example.com"
MParticle.sharedInstance().identity.modify(identityRequest, completion: identityCallback)

In this example, the SDK will remove the email of the current user, or will do nothing if the user has no email on this device:

MPIdentityApiRequest *identityRequest = [MPIdentityApiRequest requestWithEmptyUser];
identityRequest.email = nil
[[[MParticle sharedInstance] identity] modify:identityRequest completion:identityCallback];
var identityRequest = MPIdentityApiRequest.withEmptyUser()
identityRequest.email = nil
MParticle.sharedInstance().identity.modify(identityRequest, completion: identityCallback)

Advertising ID (IDFA)

As of Apple SDK 8.0, mParticle no longer automatically collects the Apple Advertising ID (IDFA). This is to ensure that developers can make their own decision on user privacy and data use, especially as it pertains to Apple policy changes arriving with iOS 14. To include IDFA in your mParticle data, you must must now manually query and provide the IDFA to the mParticle SDK. For more information on migrating to our Apple SDK 8.0, check out the dedicated iOS 14 guide as well as the SDK migration guide.

MPIdentityApiRequest *identityRequest = [MPIdentityApiRequest requestWithEmptyUser];
[identityRequest setIdentity: [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString] identityType:MPIdentityIOSAdvertiserId];
[[[MParticle sharedInstance] identity] modify:identityRequest completion:identityCallback];
let identityRequest = MPIdentityApiRequest.withEmptyUser()
identityRequest.setIdentity(ASIdentifierManager.shared().advertisingIdentifier.uuidString, identityType: MPIdentity.iosAdvertiserId)
MParticle.sharedInstance().identity.modify(identityRequest, completion: identityCallback)

Error Handling

The mParticle IDSync API is intended to be central to your app’s state and is designed to be fast and highly-available. Similar to how your app may prevent users from logging in, logging out, or modifying their state without an internet connection - we intend you to treat these APIs as gating operations in order to maintain a consistent user state. The SDK will not retry API calls automatically, but provides callback APIs such that you can do so according to your business logic. The tolerance you have for retry and inconsistent state is up to your product requirements.

If you do not wish to handle errors, you may see data consistency issues at scale. It’s recommended to at least monitor for errors during your implementation.

Your IDSync callback block will be invoked with one of two objects:

  • MPIdentityApiResult: A result object containing the new or updated user object.
  • NSError/Error: An error object containing a code and description if the IDSync call failed
id identityCallback = ^(MPIdentityApiResult *_Nullable apiResult, NSError *_Nullable error) {
    if (apiResult) {
        //IDSync request succeeded, mutate attributes or query for the MPID as needed
        [apiResult.user setUserAttribute:@"example attribute key"
                                   value:@"example attribute key"];
    } else {
        NSLog(@"%@", error.userInfo);
        switch (error.code) {
            case MPIdentityErrorResponseCodeClientNoConnection:
            case MPIdentityErrorResponseCodeClientSideTimeout:
                //retry the IDSync request
                break;
            case MPIdentityErrorResponseCodeRequestInProgress:
            case MPIdentityErrorResponseCodeRetry:
                //inspect your implementation if this occurs frequency
                //otherwise retry the IDSync request
                break;
                
            default:
                // inspect error.userInfo to determine why the request failed
                // this typically means an implementation issue
                break;
        }
    }
};
let identityCallback = {(result: MPIdentityApiResult?, error: Error?) in
    if let user = result?.user {
        //IDSync request succeeded, mutate attributes or query for the MPID as needed
        user.setUserAttribute("example attribute key", value: "example attribute value")
    } else if let error = error {
        print(error.localizedDescription)
        if let resultCode = MPIdentityErrorResponseCode(rawValue: UInt((error as NSError).code)) {
            switch (resultCode) {
            case .clientNoConnection, .clientSideTimeout:
                //retry the IDSync request
                break;
            case .requestInProgress, .retry:
                //inspect your implementation if this occurs frequency
                //otherwise retry the IDSync request
                break;
            default:
                // inspect error.localizedDescription to determine why the request failed
                // this typically means an implementation issue
                break;
            }
        }
    }
}

Status Codes

When an IDSync callback block in invoked with a failure, you can inspect the code property to determine the cause. This property is meant to describe the result of the invocation of the respective iOS SDK IDSync API. It may either contain a client-side generated value, or an actual HTTP status code.

Client-side Codes

The NSError code property may contain the following client-side codes, defined within the MPIdentityErrorResponseCode enum:

MPIdentityErrorResponseCode Description
MPIdentityErrorResponseCodeRequestInProgress The IDSync HTTP request was not performed as there is already an IDSync HTTP request in progress
MPIdentityErrorResponseCodeClientSideTimeout The IDSync HTTP request failed due to a TCP connection timeout.
MPIdentityErrorResponseCodeClientNoConnection The IDSync HTTP request failed due to lack of network coverage.
MPIdentityErrorResponseCodeSSLError The IDSync HTTP request failed due to an SSL configuration issue. The SDK pins the mParticle SSL certificate which requires custom initialization via the MPNetworkOptions API to disable.
MPIdentityErrorResponseCodeOptOut The IDSync HTTP request was not performed due to the SDK being disabled due to opt-out.
MPIdentityErrorResponseCodeUnknown The IDSync HTTP request failed due to an unknown error. This should be rare and could mean the app is in a bad memory state.

HTTP Status Codes

The NSError code property may contain the following server generated HTTP status codes, some of which are defined within the MPIdentityErrorResponseCode enum for your convenience:

Value Description
400 The IDSync HTTP call failed due to an invalid request body. Inspect the error.userInfo object for more information.
401 The IDSync HTTP call failed due to an authentication error. Verify that your API key is correct.
403 Forbidden Aliasing is not provisioned for your mParticle workspace. Contact your mParticle account representative to have aliasing provisioned.
429 The IDSync HTTP call was throttled and should be retried. This may indicate a user “hotkey” or an incorrect implementation resulting in a higher than expected volume of IDSync requests. Learn more about API throttling in Default Service Limits.
5xx The IDSync HTTP call failed due to an mParticle server-side issue. This should never happen under typical circumstances. Check the mParticle status page if this is occuring.

User Aliasing

As mentioned in the overview above, the IDSync API is meant to transition the SDK’s “current user.” The SDK maintains values in persistence that are associated with each user, such as user attributes. On completion of a successful login, you can copy user data from the previous user to the new user.

If your organization uses Profile Link or Profile Conversion strategies, you can also create a request to alias the previous user to the current user. See our main documentation on aliasing for more information.

// Basic - Call alias as the result of a successful login
[MParticle.sharedInstance.identity loginWithCompletion:^(MPIdentityApiResult * _Nullable apiResult, NSError * _Nullable error) {
    // Successful login request returns new and previous users
    MParticleUser *newUser = apiResult.user;
    MParticleUser *previousUser = apiResult.previousUser;
    
    // Copy anything attributes and products from previous to new user.
    // This example copies everything
    [newUser setUserAttributes:previousUser.userAttributes];
    [newUser.cart addAllProducts:previousUser.cart.products shouldLogEvents:NO];
    
    // Create and send the alias request
    MPAliasRequest *request = [MPAliasRequest requestWithSourceUser:previousUser destinationUser:newUser];
    [MParticle.sharedInstance.identity aliasUsers:request];
}];

// Call alias at any time

// The getAllUsers API returns users in reverse chronological order
MParticleUser *sourceUser = MParticle.sharedInstance.identity.getAllUsers[1];
MParticleUser *destinationUser = MParticle.sharedInstance.identity.getAllUsers[0];

MPAliasRequest *request = [MPAliasRequest requestWithSourceMPID:sourceUser.userId
                                                destinationMPID:destinationUser.userId
                                                      startTime:sourceUser.firstSeen // must be within 90 days
                                                        endTime:sourceUser.lastSeen]; // must be between startTime and now
[MParticle.sharedInstance.identity aliasUsers:request];
// Basic - Call alias as the result of a successful login
MParticle.sharedInstance().identity.login(completion: { (apiResult: MPIdentityApiResult?, error: Error?) in
    guard let apiResult = apiResult else { return }
    
    // Successful login request returns new and previous users
    let newUser = apiResult.user
    guard let previousUser = apiResult.previousUser else { return }
    
    // Copy attributes from previous to new user.
    newUser.userAttributes = previousUser.userAttributes
    
    // Create and send the alias request
    let request = MPAliasRequest(sourceUser:previousUser, destinationUser:newUser)
    MParticle.sharedInstance().identity.aliasUsers(request)
})

// Call alias at any time

// The getAllUsers API returns users in reverse chronological order
let allUsers = MParticle.sharedInstance().identity.getAllUsers();
if allUsers.count >= 2 {
    let sourceUser = allUsers[1];
    let destinationUser = allUsers[0];

    let request = MPAliasRequest(sourceMPID: sourceUser.userId,
                                    destinationMPID: destinationUser.userId,
                                    startTime: sourceUser.firstSeen, // must be within 90 days
                                    endTime: sourceUser.lastSeen) // must be between startTime and now

    MParticle.sharedInstance().identity.aliasUsers(request)
}

Supported Identity Types

See the table below and the complete API reference for supported user identity types:

MPIdentity Description
MPIdentityCustomerId If you have an internal ID for your customer
MPIdentityEmail The user’s email address
MPIdentityOther Any other identifier that can contribute to user identification
MPIdentityOther2 Any other identifier that can contribute to user identification
MPIdentityOther3 Any other identifier that can contribute to user identification
MPIdentityOther4 Any other identifier that can contribute to user identification
MPIdentityOther5 Any other identifier that can contribute to user identification
MPIdentityOther6 Any other identifier that can contribute to user identification
MPIdentityOther7 Any other identifier that can contribute to user identification
MPIdentityOther8 Any other identifier that can contribute to user identification
MPIdentityOther9 Any other identifier that can contribute to user identification
MPIdentityOther10 Any other identifier that can contribute to user identification
MPIdentityMobileNumber The user’s mobile number
MPIdentityPhoneNumber2 Any other phone number for the user
MPIdentityPhoneNumber3 Any other phone number for the user
MPIdentityFacebook The user’s Facebook ID
MPIdentityFacebookCustomAudienceId The user’s Facebook App User ID that can be retrieved through the Facebook SDK
MPIdentityGoogle The user’s Google ID
MPIdentityTwitter The user’s Twitter ID
MPIdentityMicrosoft The user’s Microsoft ID
MPIdentityYahoo The user’s Yahoo ID
MPIdentityIOSAdvertiserId The device advertiser identifier
MPIdentityIOSVendorId The device vendor identifier
MPIdentityPushToken The token provided to send push notications to this user
MPIdentityDeviceApplicationStamp The device application stamp

Was this page helpful?

    Last Updated: November 27, 2024