Issues during integration? See FAQ below.
Before You Begin: SDK Prerequisites
Follow the steps in Integrating a Singular SDK: Planning and Prerequisites.
These steps are prerequisites for any Singular SDK integration.
1. Installing the SDK
You can install the Singular SDK using CocoaPods, Swift Package Manager, or a Static Library.
- Download and install the latest version of CocoaPods.
-
To create a podfile, navigate to the project root folder in the Terminal and type:
pod init
-
To add the Singular SDK dependency, add the following to your project's Podfile:
pod 'Singular-SDK'
For example:
-
In your Terminal, navigate to the project root folder and run:
pod install
- From this point forward, open the Xcode workspace file .xcworkspace to open the project, instead of the .xcodeproj file.
- Create a Swift bridging header according to the instructions below.
-
In Xcode, go to File > Add Packages and enter the Singular SDK GitHub repository:
https://github.com/singular-labs/Singular-iOS-SDK
-
Update the Singular SDK version:
- Click the Add Package button.
-
Go to Build Phases > Link Binary with Libraries and add the AdServices.framework library. Be sure to mark it as Optional since it's only available for devices with iOS 14.3 and higher.
-
Go to Build Settings > Linking > Other Linker Flags and update Other Linker Flags with the following items:
- Create a Swift bridging header according to the instructions below.
-
After downloading and unzipping the SDK, add the unzipped folder to a folder in your Xcode project:
-
In Xcode, right-click Your App Name > Add Files To [Your Project Name]. In the dialog that opens, select Options > Create Groups and add the folder where you unzipped the SDK.
The following files should now be in your project: libSingular.a, Singular.h, SingularLinkParams.h, and Singular.js.
-
To add the required libraries:
- In Xcode, select Build Phases > Link Binary With Libraries.
-
Click + and add the following libraries:
Libsqlite3.0.tbd SystemConfiguration.framework Security.framework Libz.tbd AdSupport.framework iAd.framework WebKit.framework StoreKit.framework AdServices.framework (mark as Optional since it's only
available for devices with iOS 14.3 and higher).
Note: Confirm the directory where libSingular.a is located explicitly in your project's "Library Search Paths" (Build Settings > Search Paths > Library Search Paths).
If you installed the SDK using CocoaPods or the Swift Package Manager, you must create a Bridging Header for Swift to use the Obj-C libraries from the Singular SDK.
-
In your project, create a new file of type Header, and name it YourProjectName-Bridging-Header.
-
Open the file and add the following:
#import <Singular/Singular.h>
For example:
-
Go to Build Settings > Objective-C Bridging Header and add the file's relative path:
2. Setting Up a Basic SDK Integration
Important:
- To use Swift, you must have a Bridging Header (see guide above).
- If you added the Singular SDK using the Swift Package Manager, ensure you updated Build Settings > Other Linker Flags as explained above.
2.1. Importing the Singular Library
In the SceneDelegate, AppDelegate, or any file where Singular will be used, import the Singular class library to start using the Singular SDK.
// If installed with Cocoapods or Swift Package Manager
#import Singular
// If installed manually in Objective-C
#import "Singular.h"
2.2. Creating a Configuration Object
Before you initialize Singular functionality in your code, you have to create a Singular configuration object and set all your configuration options. This code block should be added in SceneDelegate (or if you are not using SceneDelegate, add it to AppDelegate).
The following code example creates a configuration object and sets some common configuration options, such as enabling SKAdNetwork in Managed Mode and setting a timeout to wait for an ATT response.
The following sections give more details about each of these options and how you can customize them.
Example: Creating a Configuration Object with Some Common Options
func getConfig() -> SingularConfig? {
print(Date(), "-- Scene Delegate getConfig")
// Create the config object with the SDK Key and SDK Secret
guard let config = SingularConfig(apiKey: Constants.APIKEY, andSecret:
Constants.SECRET) else {
return nil
}
// Set a 300 sec delay before initialization to wait for the user's ATT response
// Remove this if you are not displaying an ATT prompt!
config.waitForTrackingAuthorizationWithTimeoutInterval = 300
// Support custom ESP domains
config.espDomains = ["links.your-website-domain.com"]
// Set a handler method for deep links
config.singularLinksHandler = { params in
self.processDeeplink(params: params)
}
return config
}
- (SingularConfig *)getConfig {
NSLog(@"-- Scene Delegate getConfig");
// Create the config object with the SDK Key and SDK Secret
SingularConfig* config = [[SingularConfig alloc] initWithApiKey:APIKEY andSecret:SECRET];
// Set a 300 sec delay before initialization to wait for the user's ATT response
// Remove this if you are not displaying an ATT prompt!
config.waitForTrackingAuthorizationWithTimeoutInterval = 300;
// Support custom ESP domains
config.espDomains = @[@"links.your-website-domain.com"];
// Set a handler method for deep links
config.singularLinksHandler = ^(SingularLinkParams * params) {[self processDeeplink:params];};
return config;
}
Note: Starting with Singular iOS SDK version 12.0.6, SKAdNetwork is enabled by default.
If you are still using an older version of the SDK, you need to enable SKAdNetwork using the following code when creating the configuration object:
// Enable SKAdNetwork in Managed Mode
config.skAdNetworkEnabled = true
// Enable SKAdNetwork in Managed Mode
config.skAdNetworkEnabled = YES;
2.3. Customizing SKAdNetwork Options
SKAdNetwork is Apple's framework for determining mobile install attribution without compromising the end user's privacy. SKAdNetwork lets you measure the performance of your app marketing campaigns without sharing the user's personally identifiable information.
By default, SKAdNetwork is enabled in Managed Mode, where the conversion value is managed directly by Singular from the server side. If using Managed Mode, you don't need to add any code to your app to handle SKAdNetwork.
This allows for maximum flexibility as you can set and change your conversion values through the Singular platform without modifying your client-side code.
This server-side managed mode also helps you deal with the SKAdNetwork timers. SKAdNetwork allows you to update the conversion value within 24 hours from the time of registration to SKAdNetwork. Any call to update the conversion value extends the timer by 24 more hours. Therefore, when choosing your conversion events, you'll have to make sure the events happen within that update window. In managed mode, you can change the conversion event configuration at any time without releasing a new version of your app.
Using SKAdNetwork in Manual Mode (Advanced)
If you want to update the conversion value on your own using the app code, you first have to set the manualSkanConversionManagement flag in the Singular Config. This lets you use several SDK methods to retrieve and update the conversion value manually.
To enable Manual Mode:
func getConfig() -> SingularConfig? {
// Singular Config Options
guard let config = SingularConfig(apiKey: Constants.APIKEY,
andSecret: Constants.SECRET) else {
return nil
}
...
config.manualSkanConversionManagement = true
...
return config
}
- (SingularConfig *)getConfig {
// Singular Config Options
SingularConfig* config = [[SingularConfig alloc] initWithApiKey:APIKEY
andSecret:SECRET];
...
config.manualSkanConversionManagement = YES;
...
return config;
}
To update the conversion value:
In Manual Mode, to update the conversion value, you need to use the skanUpdateConversionValue method. You can use it wherever needed in your app's lifecycle.
Note: The skanUpdateConversionValue method will not function if you have not enabled manualSkanConversionManagement.
skanUpdateConversionValue Method | |
---|---|
Description | Manually updates the SKAdNetwork conversion value. |
Signature | (BOOL)skanUpdateConversionValue:(NSInteger)conversionValue; |
Usage Example |
|
Other SKAdNetwork methods:
To get the current conversion value, use the skanGetConversionValue method or conversionValueUpdatedCallback. Both work in Managed and Manual Mode.
skanGetConversionValue Method | |
---|---|
Description | Get the current conversion value tracked by the Singular SDK. |
Signature | (NSNumber *)skanGetConversionValue; |
Usage Example |
|
conversionValueUpdatedCallback Callback | |
Description | Get the current conversion value tracked by the Singular SDK. |
Signature | void(^conversionValueUpdatedCallback)(NSInteger); |
Usage Example |
|
2.4. Handling ATT Consent (Setting an Initialization Delay)
Displaying an ATT (App Tracking Transparency) Prompt
Starting with iOS 14.5, apps are required to ask for user consent (using the App Tracking Transparency framework) before they can access and share some user data that is helpful for tracking purposes, including the device's IDFA.
Singular highly benefits from having the IDFA to identify devices and perform install attribution (although there are ways to perform attribution without the IDFA). We strongly recommend that you ask for the user's consent to get the IDFA.
Delaying Initialization to Wait for ATT Response
By default, the Singular SDK sends a user session when it's initialized. When a session is sent from a new device, it immediately triggers Singular's attribution process - which is performed based only on the data available to Singular at that point. Therefore, it's essential to ask for consent and retrieve the IDFA before the Singular SDK sends the first session.
To delay the firing of a user session, initialize the Singular SDK with the waitForTrackingAuthorizationWithTimeoutInterval option in the Config object. This option is already included in the code sample in 2.2. Creating a Configuration Object.
func getConfig() -> SingularConfig? {
guard let config = SingularConfig(apiKey: Constants.APIKEY,
andSecret: Constants.SECRET) else {
return nil
}
...
config.waitForTrackingAuthorizationWithTimeoutInterval = 300
...
return config
}
- (SingularConfig *)getConfig {
SingularConfig* config = [[SingularConfig alloc] initWithApiKey:APIKEY
andSecret:SECRET];
...
config.waitForTrackingAuthorizationWithTimeoutInterval = 300;
...
return config;
}
Tip: When you set an initialization delay, the app flow is as follows:
- When the app opens, the Singular SDK starts recording a session and user events but does not send them to the Singular server yet.
- When App Tracking Transparency consent is granted/denied, or the set time elapses, the SDK sends the session and any queued events to the Singular server (with or without the IDFA).
- Singular then starts the attribution process, taking advantage of the IDFA if it is available.
The following table summarizes the possible scenarios using this integration:
Scenario | IDFA Availability |
The user sees the consent dialog and grants consent before the set time elapses. | IDFA is available |
The user sees the consent dialog and denies consent before the set time elapses. | IDFA is not available |
The set time expires, then the user is shown the consent dialog and grants consent. | IDFA is available only for the user events that are reported after the consent is granted |
The set time expires, then the user is shown the consent dialog and denies consent. | IDFA is not available |
The user is shown the consent dialog, exits the app without taking action, and later opens the app and grants consent after the set time has expired. | Any queued events are sent to the Singular server when the app is reopened. The IDFA is not available for these events. Any events tracked after consent is granted do have IDFA associated with them. |
The user is shown the consent dialog, exits the app without taking action, and later opens the app and denies consent. | Any queued events are sent to the Singular servers when the app is reopened. The IDFA is not available for these events or any of the events tracked afterward. |
2.5. Handling Deep Links
When a user clicks a deep link on a device that has the app installed, the app opens and shows a specific product or experience.
Singular tracking links can include deep linking functionality as well as deferred deep linking (see our Deep Linking FAQ and the Singular Links FAQ for more information).
The Singular SDK Config, implemented in the previous step, references a callback function ("processDeeplink"). The "processDeeplink" function is required to enable deep link and deferred deep link support through the Singular SDK.
Prerequisites for Implementing Deep Links
Make sure you have completed the following steps:
- Followed the instructions in Singular Links Prerequisites.
- In Xcode, added a Singular Custom Subdomain to Signing & Capabilities > Associated Domains.
- Added the app scheme to your URL Types at Info > URL Types.
- Added your Apple Developer Team ID and Scheme in the Apps page in the Singular platform.
Notes:
- If the app is already configured to use iOS Universal Links, the Universal Link domain already exists in Associated Domains and can remain. This domain should be added to the Supported Domains config option, as noted in the next section.
- You must also include the Singular custom link domain, so that Singular can track attributions from marketing campaigns and handle deep links from these campaigns.
Creating the Callback Method for the Handler
The code example below creates a callback method called processDeeplink (this method is referenced in the Config code sample above).
The block signature is void(^)(SingularLinkParams*). The SingularLinkParams contains the deep link destination, passthrough parameters, and whether the link is deferred or not.
func processDeeplink(params: SingularLinkParams!) {
// Get Deeplink data from Singular Link
let deeplink = params.getDeepLink()
let passthrough = params.getPassthrough()
let isDeferredDeeplink = params.isDeferred() ? "Yes" : "No"
// Add deep link handling code here
}
- (void)processDeeplink:(SingularLinkParams*)params{
// Get Deeplink data from Singular Link
NSString* deeplink = [params getDeepLink];
NSString* passthrough = [params getPassthrough];
NSString* isDeferredDeeplink = [params isDeferred] ?@"Yes": @"No";
// Add deep link handling code here
}
Other Link Options
The Singular SDK also supports Universal Links that aren't served by Singular. This is required for measuring attribution for partners who support deep linking, such as for Google Ads and Facebook.
For Singular iOS SDK versions 12.0.3 and above, non-Singular Universal Links are supported by default.
To support third-party deep links in older versions of the SDK:
- In older versions of the Singular iOS SDK, you need to add all associated domains (excluding sng.link) to the supportedDomains configuration option (in the Config object) every time the Singular SDK is initialized. This allows for the third-party deep link behavior but does not allow for attribution to the deep link. For attribution, you still have to use Singular tracking links.
- supportedDomains functionality assumes you have configured your app for Universal Links and currently host your own AASA file on your domain.
func getConfig() -> SingularConfig? {
// Singular Config Options
guard let config = SingularConfig(apiKey: Constants.APIKEY,
andSecret: Constants.SECRET) else {
return nil
}
...
config.supportedDomains = ["subdomain.mywebsite.com","anothersubdomain.myotherwebsite.com"]
...
return config
}
- (SingularConfig *)getConfig {
// Singular Config Options
SingularConfig* config = [[SingularConfig alloc] initWithApiKey:APIKEY
andSecret:SECRET];
...
config.supportedDomains = @[@"subdomain.mywebsite.com","anothersubdomain.myotherwebsite.com"];
...
return config;
}
The Singular SDK supports Universal Links served by ESPs (Email Service Providers).
The ESP domain must be HTTPS-enabled. Apple requires that iOS apps pull apple-app-site-association files from an HTTPS-enabled endpoint without redirects. Check with your ESP how they host this file for your app, as it may require DNS configuration on your site's DNS. Typically, the ESP will provide the steps needed to enable HTTPS.
To support an ESP domain, add the custom tracking domain to the espDomains configuration option (in the config object) every time the Singular SDK is initialized.
func getConfig() -> SingularConfig? {
// Singular Config Options
guard let config = SingularConfig(apiKey: Constants.APIKEY,
andSecret: Constants.SECRET) else {
return nil
}
...
config.espDomains = ["links.mywebsite.com"]
...
return config
}
- (SingularConfig *)getConfig {
// Singular Config Options
SingularConfig* config = [[SingularConfig alloc] initWithApiKey:APIKEY
andSecret:SECRET];
...
config.espDomains = @[@"links.mywebsite.com"];
...
return config;
}
2.6. Initializing Singular
Tip: Before proceeding, make sure you have completed the steps below!
- Added the Singular Library
- If using swift: created a Swift Bridging Header
- Added code to create the Singular Config object
- Added a deep link handler
- Enabled SKAdNetwork
- If showing the ATT: added waitForTrackingAuthorizationWithTimeoutInterval
- Test built the app successfully (the app should build without error at this stage)
The Singular SDK should be initialized every time your app is opened. This is a prerequisite to all Singular attribution functionality, and it also sends a new user session to Singular (sessions are used to calculate user retention). The SDK is initialized using the config object that you created in 2.2. Creating a Configuration Object.
Where to Add the Initialization Code?
You have to initialize the Singular SDK in every entry point to the app:
-
For iOS 13+, initialize the Singular SDK in the following SceneDelegate functions: willConnectTo session, continue userActivity, openURLContexts URLContexts.
-
For older versions of iOS that don't support SceneDelegate, initialize the SDK in the following AppDelegate functions: didFinishLaunchingWithOptions, continueUserActivity, openURL.
Initialization Code Examples
// INITIALIZE THE SDK IN THE FOLLOWING SCENEDELEGATE FUNCTIONS
// willConnectTo session
func scene(_ scene: UIScene, willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions) {
let userActivity = connectionOptions.userActivities.first
// Print IDFV to Console for use in Singular SDK Console
print(Date(), "-- Scene Delegate IDFV:",
UIDevice().identifierForVendor!.uuidString as Any)
//Initialize the Singular SDK here:
if let config = self.getConfig() {
config.userActivity = userActivity
Singular.start(config)
}
}
// continue userActivity
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
// Starts a new Singular session on continueUserActivity
if let config = self.getConfig() {
config.userActivity = userActivity
Singular.start(config)
}
}
//openURLContexts URLContexts
func scene(_ scene: UIScene, openURLContexts URLContexts:
Set<UIOpenURLContext>) {
// Starts a new Singular session on cold start from deeplink scheme
if let config = self.getConfig() {
config.openUrl = openurlString
Singular.start(config)
}
// Add custom code here to Redirect to non-Singular deep links
// ...
}
// INITIALIZE THE SDK IN THE FOLLOWING SCENEDELEGATE FUNCTIONS
// willConnectToSession
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
NSUserActivity* userActivity = [[[connectionOptions userActivities] allObjects] firstObject];
// Print identifier for Vendor (IDFV) to Xcode Console for use in Singular SDK Console
NSLog(@"-- Scene Delegate IDFV: %@", [[[UIDevice currentDevice] identifierForVendor] UUIDString]);
// Start a new Singular session from a backgrounded app
SingularConfig *config = [self getConfig];
config.userActivity = userActivity;
[Singular start:config];
}
// continueUserActivity
- (void)scene:(UIScene *)scene continueUserActivity:(NSUserActivity *)userActivity{
// Starts a new Singular session from a backgrounded App
SingularConfig *config = [self getConfig];
config.userActivity = userActivity;
[Singular start:config];
}
// openURLContexts
- (void)scene:(UIScene *)scene openURLContexts:(nonnull NSSet *)URLContexts {
// Starts a new Singular session on cold start from deeplink scheme
SingularConfig *config = [self getConfig];
config.openUrl = url;
[Singular start:config];
// Add custom code here to Redirect to Non-Singular deep links
// ....
}
// INITIALIZE THE SDK IN THE FOLLOWING APPDELEGATE FUNCTIONS
// didFinishLaunchingWithOptions
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Starts new session when user opens the app if session timeout passed/opened using Singular Link
SingularConfig *config = [self getConfig];
config.launchOptions = launchOptions;
[Singular start:config];
return YES;
}
// continueUserActivity
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity
restorationHandler:(void (^)(NSArray<id> *restorableObjects))restorationHandler {
// Starts a new session when the user opens the app using a Singular Link while it was in the background
SingularConfig *config = [self getConfig];
config.userActivity = userActivity;
[Singular start:config];
return YES;
}
// openURL
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options{
// Starts new session when user opens the app using a non-Singular link, like a traditional app scheme.
SingularConfig *config = [self getConfig];
config.openUrl = url;
[Singular start:config];
// Add custom code here to Redirect to non-Singular deep links
// ,,,
return YES;
}
Notes:
- When creating the config object, be careful to pass the correct option - userActivity or openUrl. See the sample code below and refer to the sample apps if needed.
- Remember to comply with the various privacy laws enacted in regions where you conduct business, including GDPR, CCPA, and COPPA. For more information, see SDK Opt-In and Opt-Out Practices and review the Singular SDK functions that help you comply with data privacy laws.
- To initialize the SDK, you need your Singular SDK Key and SDK Secret. You can get them in the Singular platform at Developer Tools > SDK Keys.
2.7. Sending the User ID to Singular (Optional)
The Singular SDK can send an internal user ID from your app to Singular.
- This can be any identifier, but it should not be PII (Personally Identifiable Information). For example, you should not use the user's email address.
- This identifier should also be the same internal user ID that would be captured across all platforms (web/mobile).
- If you are using Singular's Cross-Device measurement, the collection of the user ID is required across all platforms.
- Singular will expose the user ID in user-level exports and internal BI postbacks (if configured). The user ID is first-party data and will not be shared with other parties.
- The user ID persists until it is unset using the unsetCustomUserId or until the app is uninstalled. Closing/restarting the app does not unset the user ID.
To set the user ID, use the setCustomUserId method. To unset it (for example, if the user logs out of their account), call unsetCustomUserId. If multiple users use a single device, we recommend implementing a logout flow and setting and unsetting the user ID for each login and logout.
If you already know the user ID when the app opens, call setCustomUserId before initializing the Singular SDK. This way, Singular can have the user ID from the very first session. However, typically, the user ID is not available until the user registers or performs a login. In that case, call setCustomUserId after the registration.
setCustomUserId and unsetCustomUserId Methods | |
---|---|
Description | Sets and Unsets the user ID. |
Signature | (void)setCustomUserId:(NSString*)customUserId (void)unsetCustomUserId; |
Usage Example |
|
2.8. Implementing Global Properties (Optional)
The Singular SDK lets you define custom properties to be sent to the Singular servers along with every session and event sent from the app. These properties can represent any information you want about the user, the app mode/status, or anything else.
You can define up to 5 global properties. They persist between app runs (with the latest value you gave them) until you unset them or the user uninstalls the app.
Use Cases
Some use cases for global properties are:
- Pass an identifier from a third-party SDK and then use it in a postback from Singular to said third party for matching purposes.
- In a gaming app, you can define a property called "Level" and set it initially to "0". Any session and event sent from the app will be sent with "Level": "0". Once the user levels up, you reset the property to "1" and so on.
Notes:
- Global properties are currently reflected in Singular's user-level event logs (see Exporting Attribution Logs) and in postbacks. Support for global properties in Singular's aggregate reporting (the Reports page or the reporting API) will be added in the future. If you have questions about this feature or are interested in updates to global properties support, contact your Singular customer success manager.
- Each property name and value can be up to 200 characters long. If you pass a longer property name or value, it will be truncated to 200 characters.
Setting Global Properties through the Config Object
To set global properties before initializing the SDK, use the setGlobalProperty method in the Config object.
Note that since global properties and their values persist between app runs, the property you are setting may already be set to a different value. Use the overrideExisting parameter to tell the SDK whether to override an existing property with the new value or not.
setGlobalProperty Method | |
---|---|
Description | Set a global property. |
Signature | (void)setGlobalProperty:(NSString*)key withValue:(NSString*)value overrideExisting:(BOOL)overrideExisiting; |
Usage Example |
|
Setting Global Properties After Initialization
Use the following methods to set, unset, and retrieve global properties at any time in the app's run.
Notes:
- If the property does not exist yet, and there are already 5 other global properties, the property will not be added.
- If the property has already been set, the overrideExisting parameter determines whether the existing value will be overridden.
- The method returns true if the property was set successfully or false otherwise.
setGlobalProperty Method | |
---|---|
Description | Set a global property to a given value. |
Signature | (BOOL) setGlobalProperty:(NSString*)key andValue:(NSString*)value overrideExisting:(BOOL)overrideExisting |
Usage Example |
|
getGlobalProperties Method | |
Description | Retrieve all the global properties and their current values as a Map. |
Signature | NSDictionary*) getGlobalProperties |
Usage Example |
|
unsetGlobalProperty Method | |
Description | Remove a global property. |
Signature | (void) unsetGlobalProperty:(NSString*)key |
Usage Example |
|
clearGlobalProperties Method | |
Description | Remove all global properties. |
Signature | (void) clearGlobalProperties |
Usage Example |
|
2.9. Modifying the Session Timeout (Optional)
By default, if the app runs in the background for 60 seconds or more before returning to the foreground, the SDK will register a new session. To change this timeout value, use the setSessionTimeout method and add it to the Config.
setSessionTimeout Method | |
---|---|
Description | Change the session timeout value. |
Signature | (void)setSessionTimeout:(int)timeout |
Usage Example |
|
3. Tracking Events and Revenue
Note: For details on planning user events, see Will the App Track User Events? in the SDK Planning and Prerequisites guide.
Note: We recommend sending all in-app events to the Singular server using Singular SDK methods in your app. If you plan to send events to Singular from another provider or an internal server, see the Hybrid Event Tracking section below.
3.1. Tracking Events
Singular can collect data about in-app events to help analyze the performance of your campaigns and measure KPIs. For example, your organization may want to collect data about user logins, registrations, tutorial completions, or leveling up in a gaming app.
The list of events sent to Singular (with the accompanying attributes) should be compiled by the UA/marketing/business team based on your Marketing KPIs.
For more details on planning user events, see Will the App Track User Events? in the SDK Planning and Prerequisites guide.
In your code, send standard events to Singular using the event or eventWithArgs methods.
Note: For standard events, use the event's iOS name as it appears in the iOS SDK List of Standard Events and Attributes, e.g., EVENT_SNG_LOGIN.
For custom events, events that your organization wants to measure that do not match any of Singular's standard events, use any custom name (maximum of 32 characters). We recommend using names in English for compatibility with any ad network partners that may receive the event from Singular for optimization purposes.
event Method | |
---|---|
Description | Send a user event to Singular for tracking. |
Signature | (void)event:(NSString *)name |
Usage Example |
|
eventWithArgs Method | |
Description | Send a user event to Singular for tracking, with additional information. |
Signature | (void)eventWithArgs:(NSString *)name, ... |
Usage Example | The following example sends a Content View event with the recommended standard attributes.
|
3.2. Tracking Revenue
Singular can collect data about revenue gained through the app to help analyze the performance and ROI of your campaigns. Singular will make the data available in reports, log export, and postbacks.
Note:If you app supports IAP tracking through the App Store, this method is recommended. If you are not using App Store IAP, see the alternative methods below.
Reporting Revenue Through IAP Tracking (Recommended)
To report revenue events to Singular, use the iapComplete SDK method. This method sends an IAP (Apple's In-App Purchase) revenue event to Singular with:
- All the transaction details, which Singular will use to enrich reports.
- The transaction receipt, which can be used to validate the transaction and analyze or prevent fraud attempts.
Notes:
- When using the iapComplete, you must include the SKPaymentTransaction object in the event.
- Any revenue reported in a different currency will be auto-converted to your organization's preferred currency, as set in your Singular account.
iapComplete Method | |
---|---|
Description | Send a revenue event to Singular with the transaction receipt. |
Signature | (void)iapComplete:(id)transaction (void)iapComplete:(id)transaction withName:(NSString *)name; |
Usage Example |
|
Alternative Revenue Event Reporting
While Singular recommends using iapComplete, we also provide two alternative methods to report revenue events to Singular, in case your app doesn't use App Store IAP tracking.
The revenue and customRevenue methods let you specify the transaction amount and currency manually, as well as optional additional details, such as the product serial number and quantity, etc. The customRevenue method also lets you pass a custom event name.
Note that if you use these methods, Singular does not get the transaction receipt and cannot validate the transaction.
Note: Pass currency as a three-letter ISO 4217 currency code, e.g., "USD," "EUR", "INR".
revenue Method | |
---|---|
Description | Send a revenue event to Singular with the revenue amount and currency and optional additional details. |
Signature | (void)revenue:(NSString *)currency amount:(double)amount; (void)revenue:(NSString *)currency amount:(double)amount productSKU:(NSString *)productSKU productName:(NSString *)productName productCategory:(NSString *)productCategory productQuantity:(int)productQuantity productPrice:(double)productPrice; (void)revenue:(NSString *)currency amount:(double)amount withAttributes:(NSDictionary*)attributes; |
Usage Example |
|
customRevenue Method | |
Description | Send a revenue event to Singular with an event name as well as the revenue amount and currency and optional additional details. |
Signature | (void)customRevenue:(NSString *)eventName currency:(NSString *)currency amount:(double)amount; (void)customRevenue:(NSString *)eventName currency:(NSString *)currency amount:(double)amount productSKU:(NSString *)productSKU productName:(NSString *)productName productCategory:(NSString *)productCategory productQuantity:(int)productQuantity productPrice:(double)productPrice; (void)customRevenue:(NSString*)eventname currency:(NSString *)currency amount:(double)amount withAttributes:(NSDictionary*)attributes; |
Usage Example |
|
3.3. Hybrid Event Tracking (Advanced)
Singular recommends sending all your events and revenue through the Singular SDK integrated into your app. However, if needed, Singular can collect events and revenue from other sources.
The party sending the data must comply with Singular's Server-to-Server Event documentation requirements and provide the matching device identifier to correctly attribute an event.
If the provider or server sends events or revenue with an incorrect identifier and data points, this will cause discrepancies in your data in Singular.
Hybrid Event Tracking Guides
Endpoint:
Send the events to the Singular S2S event endpoint at https://s2s.singular.net/api/v1/evt, adding parameters as needed using the table below.
Requirements:
- Capture the device identifiers (IDFA and IDFV) used by the Singular SDK and store this data with the User ID on the server side. Because device identifiers may change for a user, be sure to to update the identifiers when a user generates an app session. This guarantees the server-side event will be attributed to the correct device.
- Server-side events are platform specific and should only be sent with the device identifier matching the device platform (e.g., IDFA or IDFV for iOS devices).
- You can use the Singular Internal BI postback mechanism to push an event in real time to your internal endpoint so that you can update the data set on the server side. See the Internal BI Postback FAQ.
- In the example below, the iOS required data points are marked with a "Y", for a Server side event. For Revenue events, you must include the Amount, Currency, and Revenue Flag.
Call Parameters:
Parameter | Required? | Description | Example Value |
---|---|---|---|
a= | v | SDK Key | |
&i= | v | Bundle ID | com.myapp |
&p= | v | Platform | iOS |
&use_ip= | v* | Flag to use the Server IP address | TRUE |
&idfa | v | Device IDFA | 131B7AF2-52E5-41A1-AA0B-C036037575AC |
&idfv | v | Device IDFV | 230F6839-290B-4BF9-8C4E-F165FE5980CF |
&custom_user_id= | v | User ID | user123456789 |
&n= | v | Name of Event | s2sPurchase |
&e= | Event Arguments |
{'sampleKey1':'sampleValue1', 'sampleKey2':'sampleValue2', 'sampleKey3':'sampleValue3'} |
|
&is_revenue= | Required for revenue events | Revenue Flag | TRUE |
&amt= | Revenue Amount | 2.99 | |
&cur= | Revenue ISO 4217 currency code | USD |
Sample Request:
https://s2s.singular.net/api/v1/evt?a=<SDK KEY>&i=com.myapp&p=iOS&use_ip=true&idfa131B7AF2-52E5-41A1-AA0B-C036037575AC&idfv230F6839-290B-4BF9-8C4E-F165FE5980CF&custom_user_id=user123456789&n=s2sPurchase&e=%7B%27sampleKey1%27%3A%27sampleValue1%27%2C%27sampleKey2%27%3A%27sampleValue2%27%2C%27sampleKey3%27%3A%27sampleValue3%27%7D&is_revenue=true&amt=2.99&cur=USD
Known Issues:
- For newly installed apps, if server-side events are received before the Singular SDK sent the first session to the Singular server with a device ID, then Singular will start the attribution process based on the event and lacking the device ID, resulting in an organic attribution.
- If the device identifier used by the Singular SDK differs from the device identifier specified in the server-side Event, the event will be attributed incorrectly.
Requirements:
- Send device identifier data to the revenue provider from the app. For RevenueCat, learn more in the RevenueCat documentation.
Known Issues:
- For newly installed apps, if server-side events are received before the Singular SDK sends the first session to the Singular server with a device ID, then Singular will start the attribution process based on the event and lacking the device ID, resulting in an organic attribution. This may cause a discrepancy until all the revenue provider's users (device IDs) have been seen by the Singular SDK.
For Segment to send events to Singular in parallel with the Singular SDK, you have to create a Cloud-Mode integration in Segment. You must also disable collecting Segment Lifecyle events or block them from the Singular destination.
Requirements:
- Log in to Segment, search for "Singular" in the Destinations Catalog, and confirm the source you'd like to connect to.
- Enter your Singular SDK Key.
Known Issues:
- For newly installed apps, if server-side events are received before the Singular SDK sends the first session to the Singular server with a device ID, then Singular will start the attribution process based on the event and lacking the device ID, resulting in an organic attribution. This may cause a discrepancy until all Segment users (device IDs) have been seen by the Singular SDK.
4. Advanced Options
Creating Short Referrer Links
Note: This functionality is available in SDK version 11.0.8+.
Use the createReferrerShortLink method to generate a shortened share link for the User to share the app with friends. Define the referring user details in your app code when the link is created. This allows for tracking referrer attributions in reporting.
To create a short link:
- Build a Singular Custom Source Link with defined deep links, that leads to your app download (see the Singular Links FAQ). This link will be referred to as a base link in the code below.
- Any campaign override parameters to add to the link dynamically (see Tracking Link Parameters for the list of options).
- The Name and ID of the referring user, in order to track new app installs back to the user who shared the link.
Use the createReferrerShortLink method to generate the short link as in the example below.
createReferrerShortLink Method | |
---|---|
Description | Use the createReferrerShortLink method to generate a shortened share link for the User to share the app with friends. |
Signature | (void)createReferrerShortLink:(NSString *)baseLink referrerName:(NSString *)referrerName referrerId:(NSString *)referrerId passthroughParams:(NSDictionary *)passthroughParams completionHandler:(void(^)(NSString *, NSError *))completionHandler; |
Usage Example |
|
Adding Ad Revenue Attribution Support
Note: Starting in SDK version 11.0.0, Singular added the option to set up ad revenue attribution through the Singular SDK. Ad revenue attribution can still be set up using API calls, without updating the Singular SDK in the apps. However, if you want to measure ad revenue for SKAdNetwork campaigns, it is required to set up ad revenue attribution through the SDK.
To add ad revenue attribution support in the Singular SDK:
- Contact your Singular Customer Success Manager to enable ad revenue attribution for your account.
- Make sure you are using the latest version of the Singular SDK.
- Add the appropriate code snippet to your Singular SDK integration, depending on the mediation platform used for ad revenue data.
// Note: This feature needs to be enabled in your Admob account.
// See https://support.google.com/admob/answer/11322405#getstarted
GADRewardedAd* rewardedAd;
[GADRewardedAd loadWithAdUnitID:@"AD_UNIT_ID"
request:request
completionHandler:^(GADRewardedAd *ad, NSError *error) {
if (error) {
NSLog(@"Rewarded ad failed to load with error: %@", [error localizedDescription]);
return;
}
self.rewardedAd = ad;
self.rewardedAd.paidEventHandler = ^void(GADAdValue *_Nonnull adValue){
GADAdValue* impressionData = adValue;
SingularAdData* data = [[SingularAdData alloc] initWithAdPlatfrom:@"Admob"
withCurrency:[impressionData currencyCode]
withRevenue:[impressionData value]];
}
}];
// The object received from AppLovin MAX's event, didReceivedMessage
ALCMessage* message;
SingularAdData* data = [[SingularAdData alloc] initWithAdPlatfrom:@"AppLovin" withCurrency:@"USD" withRevenue:message.data[@"revenue"] doubleValue];
[Singular adRevenue:data];
// The object received from IronSource's event, impressionDataDidSucceed
ISImpressionData* impressionData;
SingularAdData* data = [[SingularAdData alloc] initWithAdPlatfrom:@"IronSource"
withCurrency:@"USD"
withRevenue:impressionData.revenue];
[Singular adRevenue:data];
// Ensure that the ARM SDK Postbacks Flag in IronSource is turned on
// See https://developers.is.com/ironsource-mobile/general/ad-revenue-measurement-postbacks/#step-1
//Set impressionDelegate
[TradPlus sharedInstance].impressionDelegate = self;
//TradPlusAdImpression Callback
- (void)tradPlusAdImpression:(NSDictionary *)adInfo
{
NSString *currency = @"USD";
CGFloat revenue = [adInfo[@"ecpm"] floatValue]/1000.0;
SingularAdData *data = [[SingularAdData alloc]
initWithAdPlatfrom:@"TradPlus"
withCurrency:currency
withRevenue:@(revenue)];
[Singular adRevenue:data];
}
// Initialize the SingularAdData object with the relevant data
SingularAdData* data = [[SingularAdData alloc]
initWithAdPlatfrom:@"YOUR_AD_PLATFORM"
withCurrency:@"CURRENCY_CODE"
withRevenue:[NSNumber numberWithDouble:9.90]];
// Report the data to Singular
[Singular adRevenue:data];
Note: Pass currency as a three-letter ISO 4217 currency code, e.g., "USD," "EUR", "INR".
Tracking Uninstalls
Note: Uninstall tracking is only available to Enterprise customers. Additionally, uninstall tracking requires the app to support push notifications. See Apple's guide to implementing APNS.
To configure uninstall tracking:
- Enable the app in Singular by following the guide: Setting Up iOS Install Tracking.
- In the app, send Singular the device token returned from the Apple Push Notification Service (APNS). To pass the device token to Singular use the registerDeviceTokenForUninstall or registerDeviceToken method. Do this before the Singular SDK is Initialized. This must be called from the AppDelegate didRegisterForRemoteNotificationsWithDeviceToken method.
Note: If you are already retrieving a device token from an existing push notification implementation, you can use that value.
The APNS token is usually binary data in the native form. Pass the token as received from APNS. If the app alters the token data type pass it as a hex-encoded string, e.g.: b0adf7c9730763f88e1a048e28c68a9f806ed032fb522debff5bfba010a9b052
registerDeviceTokenForUninstall Method | |
---|---|
Description | Pass the device token returned from APNS. |
Signature | + (void)registerDeviceTokenForUninstall:(NSData*)deviceToken; |
Usage Example |
|
Singular SDK JavaScript Interface
Singular provides a JavaScript interface that you can use to call Singular in your app.
For example, if you set up the JavaScript interface, you can send events to Singular from JavaScript code as follows:
Singular.event('event');
Singular.event('test', JSON.stringify({"a1":"bar", "a2":"boo", "a3":"baz"}));
Supported Methods in JavaScript
The interface supports the following SDK methods:
- setCustomUserID
- unsetCustomUserID
- event
- revenue
Enabling the JavaScript Interface
Note: Starting in iOS 8.0+ Apple recommends using WKWebView to add web content to your app. Do not use UIWebView or WebView. See Apple's WKWebView documentation for more information.
To enable the JavaScript interface when using WKWebView, you need to add some code to the webView method of the WKNavigationDelegate protocol (this protocol helps you implement custom behaviors triggered when a web view handles a navigation request).
extension ViewController: WKNavigationDelegate {
func webView(_: WKWebView, decidePolicyFor: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
// Singular handler
let js = "typeof(Singular)"
webView.evaluateJavaScript(js) { (result, error) -> Void in
if let resultString = result as? String {
if resultString.isEqual("undefined") {
do {
let contents = try String(contentsOfFile:
Bundle.main.path(forResource: "Singular", ofType: "js")!)
self.webView.evaluateJavaScript(contents, completionHandler: nil)
} catch { }
}
else {
print(decidePolicyFor.request)
Singular.processJSRequestWK(self.webView, withURL:decidePolicyFor.request)
}
}
}
// rest of your code goes here
}
}
5. Complying with Data Privacy Laws
Singular provides privacy-safeguarding functionality to help you cooperate with any partners who may be complying with consumer privacy laws such as GDPR and CCPA (California Consumer Privacy Act). These partners want to be notified if the end-user has consented to share their private information.
LimitDataSharing
If you have implemented a way to ask users for consent to share their information, use the limitDataSharing method to notify Singular of the user's choice:
- Use limitDataSharing:NO to indicate that the user consented (opted in) to share their information.
- Use limitDataSharing:YES if the user did not consent.
Singular will pass this information on to partners who require it in order to comply with relevant regulations.
Note: The use of the method is optional, but there may be attribution information that the partner will share with Singular only if specifically notified that the user has opted in.
limitDataSharing Method | |
---|---|
Description | Notify Singular of user consent (opt-in) for sharing private data. |
Signature | (void)limitDataSharing:(BOOL)shouldLimitDataSharing; |
Usage Example |
|
Additional Methods for GDPR Compliance
The Singular SDK provides several methods to help you comply with GDPR policies and let Singular know about user consent or non-consent for tracking.
trackingOptIn Method | |
---|---|
Description | Notify Singular of user consent for tracking (opt-in). |
Signature | (void)trackingOptIn; |
Usage Example |
|
stopAllTracking Method | |
Description | Stop all tracking activities for this user on this app. |
Signature | (void)stopAllTracking; |
Usage Example |
Important: Calling this method disables the SDK, even between app restarts (the state is persistent). The only way to turn it off is by calling the resumeAllTracking method.
|
resumeAllTracking Method | |
Description | Resume tracking activities for this user on this app. |
Signature | (void)resumeAllTracking; |
Usage Example |
|
isAllTrackingStopped Method | |
Description | Check the status of tracking activities for this user on this app. |
Signature | (BOOL)isAllTrackingStopped; |
Usage Example |
|
Frequently Asked Questions and Issues
Refer to this section if you encounter any issues or errors when building your test app.
- Check that the Bridging Header was created.
- Validate the Bridging Header file is linked in Build Settings > Objective-C Bridging Header.
In some cases, the iOS Simulator requires arm64 to be excluded in Build Settings > Excluded Architectures.
Global Properties are currently not displayed in the Testing Console. They will be added in the future. Use Export Logs to validate this functionality.
You can ignore this error, as it is expected when SKAdNetwork has not seen an impression from a campaign (see Apple's response to this question).
The following common logging errors can be ignored:
- [logging] duplicate column name: singular_link in "ALTER TABLE sessions ADD COLUMN singular_link TEXT DEFAULT NULL"
- [logging] duplicate column name: payload in "ALTER TABLE sessions ADD COLUMN payload TEXT DEFAULT NULL"
- [logging] duplicate column name: sequence in "ALTER TABLE events ADD COLUMN sequence INTEGER DEFAULT -1"
- [logging] duplicate column name: payload in "ALTER TABLE events ADD COLUMN payload TEXT DEFAULT NULL"