# TapResearch Publisher Documentation — SDK — iOS # Source: https://supply-docs.tapresearch.com · generated at build time, do not edit by hand. # Each section below is one documentation page. # iOS Source: https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/ios :::tip What you'll do 1. [Install the SDK](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/ios#installation) 2. [Set up reward callbacks](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/ios#callbacks) 3. [Initialize the SDK](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/ios#initialization) 4. [Display a placement](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/ios#displaying-a-placement) Later sections cover user attributes, the user identifier, placement details, custom parameters, and more. **Testing?** Your app starts in test mode, so you'll need a [test device](https://supply-docs.tapresearch.com/docs/3.x/testing-and-qa) to see content while you build. ::: ## Installation See the [iOS example apps](https://github.com/TapResearch/demo-apps/tree/master/ios) on GitHub. :::note Minimum iOS version: 13.0, or 15.0 for SDK 3.8.1 and later. ::: Replace `` below with your SDK version from [GitHub releases](https://github.com/TapResearch/TapResearch-iOS-SDK/releases). ### CocoaPods ```ruby title="Podfile" platform :ios, '13.0' # Use '15.0' for SDK 3.8.1 and later. use_frameworks! target 'MyApp' do pod 'TapResearch', '' # Omit the GitHub tag's leading "v". end ``` Then run `pod install` in the Terminal. ### Swift Package Manager Add the following URL in the Xcode Swift Package Manager: ```text https://github.com/TapResearch/TapResearch-iOS-SDK ``` * Set the Dependency Rule to **Exact Version** or **Up to Next Major Version** and enter your SDK version * Set "Add to Project" to your project * Click "Add Package" In the resulting "Choose Package Product for TapResearch-iOS-SDK" select the TapResearchSDK row and click "Add Package". :::note Adding the package with an AI agent An agent running **outside** Xcode (a terminal or IDE agent) can add this Swift Package by editing your Xcode project file directly. An agent running **inside** Xcode (for example Xcode's built-in coding assistant) can't — Xcode holds the project file open, so it can't be modified while Xcode is running. In that case, add the package yourself with the steps above, then hand control back to the agent to continue. ::: ### Manual installation Download the source archive for a release from [GitHub releases](https://github.com/TapResearch/TapResearch-iOS-SDK/releases), drag `TapResearchSDK.xcframework` into your project, and set it to **Embed & Sign** under **Frameworks, Libraries, and Embedded Content**. ### Importing the SDK Import the SDK in each file that calls it: ```swift import TapResearchSDK ``` ```objectivec #import ``` ## Integration ### Callbacks The TapResearch SDK has two main delegates you can implement: `TapResearchSDKDelegate` and `TapResearchContentDelegate`. If you are implementing the delegates as their own objects make sure that the delegate objects derive from `NSObject`, for example in Swift: `class MyDelegates: NSObject, TapResearchSDKDelegate {`. #### TapResearchSDKDelegate - **`onTapResearchSdkReady`** (required): Called when the SDK is ready for use. **We recommend showing content only after this callback is called.** - **`onTapResearchDidError`** (required): Called when an error has occurred in the TapResearch SDK. For the full list, see the [error codes page](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/sdk-error-codes). - **`onTapResearchDidReceiveRewards`** (optional): Called when a user has earned a reward(s). You can implement it here or set a separate [reward delegate](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/ios#tapresearchrewarddelegate). - **`onTapResearchQuickQuestionResponse`** (optional): Called when a quick question result is being returned. The class that conforms to the `TapResearchSDKDelegate` protocol (ideally your `SceneDelegate`) must implement `onTapResearchSdkReady` and `onTapResearchDidError`. ##### Reward object Each reward is a `TRReward`. See [TRReward](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/tr-reward) for its properties, including the iOS `payoutEvent` values. ##### Quick Question response New to Quick Questions? See [Quick Questions](https://supply-docs.tapresearch.com/docs/3.x/features/quick-questions) for what they are and the response payload. `onTapResearchQuickQuestionResponse` is an optional method of **TapResearchSDKDelegate**. It is called when a Quick Question response is being returned, and receives a **TRQQDataPayload** object. Use a class to implement the SDK's delegates and pass it to TapResearch at initialization. In UIKit you can adopt the protocol on your `SceneDelegate` instead. ```swift title="TapResearchSDKDelegates.swift" import TapResearchSDK class TapResearchSDKDelegates: NSObject, TapResearchSDKDelegate { func onTapResearchSdkReady() { // The SDK is ready: send user attributes, show content, etc. if let error = TapResearch.sendUserAttributes(attributes: ["attribute1": "some player attribute", "a_number": 12]) { print("sendUserAttributes: \(error.code) \(error.localizedDescription)") } } func onTapResearchDidError(_ error: NSError) { print("onTapResearchDidError: \(error.code) \(error.localizedDescription)") } func onTapResearchDidReceiveRewards(_ rewards: [TRReward]) { for reward in rewards { print("reward: currency = \(reward.currencyName ?? "unknown"), amount = \(reward.rewardAmount)") } } func onTapResearchQuickQuestionResponse(_ qqPayload: TRQQDataPayload) { for question: TRQQDataPayloadQuestion in qqPayload.questions { // ... } } } ``` ```objectivec title="SceneDelegate.m" @interface SceneDelegate () @end @implementation SceneDelegate - (void)onTapResearchSdkReady { NSLog(@"onTapResearchSdkReady"); } - (void)onTapResearchDidError:(NSError *)error { NSLog(@"onTapResearchDidError: %ld %@", (long)error.code, error.localizedDescription); } - (void)onTapResearchDidReceiveRewards:(NSArray *)rewards { NSLog(@"onTapResearchDidReceiveRewards: %lu reward(s)", (unsigned long)rewards.count); } - (void)onTapResearchQuickQuestionResponse:(TRQQDataPayload *)qqPayload { NSLog(@"onTapResearchQuickQuestionResponse: %@", qqPayload); } @end ``` #### TapResearchRewardDelegate - **`onTapResearchDidReceiveRewards`**: Called when a user has earned a reward(s). Implementing `onTapResearchDidReceiveRewards` on your `TapResearchSDKDelegate` is optional. If you implement it, rewards can be sent to your app as soon as the SDK is ready. If not, your app will not receive any rewards until a reward delegate has been set. ##### Setting a reward delegate To set a reward handler when you are ready to receive rewards, use: ```swift TapResearch.setRewardDelegate(myRewardDelegate) ``` ```objectivec [TapResearch setRewardDelegate:myRewardDelegate]; ``` The object you pass in must conform to `TapResearchRewardDelegate` and implement `onTapResearchDidReceiveRewards`. When you no longer need the reward delegate you can simply pass `nil` to the same SDK function. :::warning If you set the reward delegate from a view controller, for example in `viewDidLoad`, make sure to call `TapResearch.setRewardDelegate(nil)` when the view controller is no longer in the stack. ::: :::note Anytime you set a new reward delegate, or nil, it replaces the previously set value. For example: if you have a reward delegate available at init time then later set another reward delegate, the original delegate will be replaced by the new one. ::: #### TapResearchQuickQuestionDelegate - **`onTapResearchQuickQuestionResponse`**: Called when a quick question result is being returned. To set a Quick Questions response handler when you are ready to receive Quick Question responses, use: ```swift TapResearch.setQuickQuestionDelegate(myQuickQuestionDelegate) ``` ```objectivec [TapResearch setQuickQuestionDelegate:myQuickQuestionDelegate]; ``` The object you pass in must conform to `TapResearchQuickQuestionDelegate` and implement `onTapResearchQuickQuestionResponse`. When you no longer need the Quick Questions response delegate you can simply pass `nil` to the same SDK function. :::warning If you set the Quick Questions response delegate from a view controller, for example in `viewDidLoad`, make sure to call `TapResearch.setQuickQuestionDelegate(nil)` when the view controller is no longer in the stack. ::: :::note Anytime you set a new Quick Questions response delegate, or nil, it replaces the previously set value. For example: if you have a Quick Questions response delegate available at init time then later set another Quick Questions response delegate, the original delegate will be replaced by the new one. ::: #### TapResearchContentDelegate - `onTapResearchContentShown`: Called when content is successfully presented to the user. - `onTapResearchContentDismissed`: Called when content is dismissed. You can use these callbacks to pause/resume audio, animations, etc. when content is shown or dismissed. ```swift title="TapResearchContentDelegates.swift" class TapResearchContentDelegates: NSObject, TapResearchContentDelegate { func onTapResearchContentShown(forPlacement placement: String) { print("\(#function): \(placement) was shown") } func onTapResearchContentDismissed(forPlacement placement: String) { print("\(#function): \(placement) was dismissed") } } ``` ```objectivec title="ViewController.m" @interface ViewController () @end @implementation ViewController - (void)onTapResearchContentShownForPlacement:(NSString *)placement { NSLog(@"onTapResearchContentShown(%@)", placement); } - (void)onTapResearchContentDismissedForPlacement:(NSString *)placement { NSLog(@"onTapResearchContentDismissed(%@)", placement); } @end ``` ### Initialization :::tip We recommend initializing TapResearch as early as possible in your application's lifecycle. This will ensure that your placements are refreshed by the time you are ready to show content. ::: To initialize the SDK, you'll need your app's API token, shown on your app's **Settings** tab in the [Publisher Dashboard](https://www.tapresearch.com/supplier_dashboard/overview). Refer to the [app setup guide](https://supply-docs.tapresearch.com/docs/3.x/setup#configure-app-settings) for more information. After obtaining your API Token, add the following snippet to the `scene:willConnectToSession:options:` method in your `SceneDelegate` class. Replace `API_TOKEN` with your API token and `UNIQUE_USER_ID` with a unique identifier within your application. :::warning Don't put the token in Info.plist Keep your API token and placement tag in a **separate Swift config file** (for example `TapResearchCredentials.swift`) and pass them to `initialize`. Do **not** add them to `Info.plist` — TapResearch never reads them from there, and on SwiftUI projects where `Info.plist` is auto-generated, hand-creating one to hold credentials will break your build. The token is only ever used in the `initialize` call. ::: If initializing the TapResearch SDK isn't possible inside the `scene:willConnectToSession:options:` method, try and do it as early as possible to ensure that your placements are refreshed by the time you are ready to show content. :::tip The user identifier passed through initialization must be **unique**! Only initialize once you are able to provide a unique identifier. Re-using the same user identifier is not supported and will prevent your users from accessing our service. ::: ```swift title="SceneDelegate.swift" func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let _ = (scene as? UIWindowScene) else { return } // SceneDelegate conforms to TapResearchSDKDelegate TapResearch.initialize(withAPIToken: apiToken, userIdentifier: userIdentifier, sdkDelegate: self) { (error: NSError?) in if let error = error { print("\(error.code) \(error.localizedDescription)") } } } ``` :::info Initialize the SDK in the `init()` method of your root view. ::: ```swift title="MainContentView.swift" let tapSDKDelegates: TapResearchSDKDelegates init() { tapSDKDelegates = TapResearchSDKDelegates() TapResearch.initialize(withAPIToken: apiToken, userIdentifier: userId, sdkDelegate: self.tapSDKDelegates) { (error: NSError?) in if let error = error { print("\(#function): \(error.code), \(error.localizedDescription)") } } } ``` ```objectivec title="SceneDelegate.m" - (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions { // SceneDelegate conforms to TapResearchSDKDelegate [TapResearch initializeWithAPIToken:API_TOKEN userIdentifier:UNIQUE_USER_ID sdkDelegate:self completion:^(NSError * _Nullable error) { if (error) { NSLog(@"Error on initialize: %ld, %@", (long)error.code, error.localizedDescription); } }]; } ``` :::note To change the user after the SDK has started, call [`setUserIdentifier`](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/ios#setting-the-user-identifier). ::: ### Send user attributes :::info See [User attributes and targeting](https://supply-docs.tapresearch.com/docs/3.x/operational-tools/user-attributes) for more. ::: User attributes are used to target specific users with content (ex: an offer). The most recent values received are used when determining which content to show. Pass a dictionary of attributes to `sendUserAttributes` after the SDK is ready. Attribute names must be strings and must not begin with `tapresearch_`, which is reserved for TapResearch. Use string or numeric values for targeting. For booleans, send `"true"`/`"false"` or `0`/`1` instead of native booleans. Set `clearPreviousAttributes` to `false` to merge new values with existing attributes, or `true` to replace the attributes you previously sent. ```swift title="ViewController.swift" func sendUserAttributes() { let date = Date() // Current date and time let formatter = ISO8601DateFormatter() let iso8601String = formatter.string(from: date) let dict: [AnyHashable: Any] = ["app-user": userIdentifier, "roller-type": "high", "roller-type-valid-until": Date().timeIntervalSince1970 + ViewController.threeHours, "some-date": iso8601String, "some-double": 1.11] if let error = TapResearch.sendUserAttributes(attributes: dict, clearPreviousAttributes: true) { print(error.localizedDescription) } } ``` ```objectivec title="ViewController.m" - (void)sendUserAttributes { NSDate *currentDate = [NSDate date]; NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init]; NSString *iso8601String = [formatter stringFromDate:currentDate]; NSTimeInterval threeHours = 3 * 60 * 60; NSNumber *rollerTypeValidUntil = @([currentDate timeIntervalSince1970] + threeHours); NSNumber *someDouble = @1.11; NSDictionary *dict = @{ @"app-user": userIdentifier, @"roller-type": @"high", @"roller-type-valid-until": rollerTypeValidUntil, @"some-date": iso8601String, @"some-double": someDouble }; NSError *error = [TapResearch sendUserAttributesWithAttributes:dict clearPreviousAttributes:YES]; if (error) { NSLog(@"%@", [error localizedDescription]); } } ``` You can also pass user attributes when you first initialize the SDK. This is done by changing the `TapResearch.initialize(...)` call to additionally pass a `userAttributes` dictionary and the `clearPreviousAttributes` flag. :::info If user attributes are known at SDK initialization, it is preferable to pass them through `initialize` compared to using `sendUserAttributes`. This will result in quicker load times for targeted content. ::: ```swift let dict: [String: Any] = ["app-user": userIdentifier, "roller-type": "high", "roller-type-valid-until": Date().timeIntervalSince1970 + ViewController.threeHours] TapResearch.initialize(withAPIToken: apiToken, userIdentifier: userIdentifier, userAttributes: dict, clearPreviousAttributes: true, sdkDelegate: self) { (error: NSError?) in if let error = error { print(error.localizedDescription) } } ``` ```objectivec NSDictionary *dict = @{ @"string": @"a string", @"number": @1 }; [TapResearch initializeWithAPIToken:apiToken userIdentifier:userIdentifier userAttributes:dict clearPreviousAttributes:YES sdkDelegate:self completion:^(NSError * _Nullable error) { if (error) { NSLog(@"Error on initialize: %ld, %@", (long)error.code, error.localizedDescription); } }]; ``` ### Setting the user identifier You can change the user identifier after the SDK is ready by calling `setUserIdentifier` with a string. ```swift TapResearch.setUserIdentifier("some-user-id") ``` ```objectivec [TapResearch setUserIdentifier:@"some-user-id" completion:nil]; ``` ### Checking if the SDK is ready The SDK lets the app know it is ready using a callback: ```swift func onTapResearchSdkReady() { } ``` ```objectivec - (void)onTapResearchSdkReady { } ``` You can also check if the SDK is ready using the `isReady` call: ```swift let ready: Bool = TapResearch.isReady() ``` ```objectivec BOOL ready = [TapResearch isReady]; ``` ### Getting placement details :::info `getPlacementDetails` is available from v3.6.3 ::: :::warning Don't cache placement details Placement details can change as our SDK refreshes placements in the background, so it is not recommended to store or cache these values. Instead, refetch the details each time you need to use them, e.g. to display something in your UI. ::: To get details for a placement call `getPlacementDetails`: ```swift let details: TRPlacementDetails? = TapResearch.getPlacementDetails("your-placement-tag") { (error: NSError?) in // Handle error } if let details { // Use the placement details } ``` ```objectivec TRPlacementDetails *details = [TapResearch getPlacementDetails:@"your-placement-tag" errorHandler:^(NSError * _Nullable error) { if (error) { // Handle the error } }]; if (details) { // Use the placement details } ``` #### The `TRPlacementDetails` objects: ```swift @objc public final class TRPlacementDetails : NSObject, Encodable { @objc public let name : String @objc public let contentType : String @objc public let currencyName : String @objc public let isSale : Bool @objc public let saleType : String? @objc public let saleEndDate : String? @objc public let saleMultiplier : Double @objc public let saleDisplayName : String? @objc public let saleTag : String? @objc public let bonusBarProgress : TRBonusBarProgress? } @objc public final class TRBonusBarProgress : NSObject, Encodable { @objc public let isActive : Bool @objc public let currentCompletes : Int @objc public let bonusWindowEndAt : String? @objc public let bonusTiers : [TRBonusTier]? @objc public let error : NSError? } @objc public final class TRBonusTier : NSObject, Encodable { @objc public let tierNumber : Int @objc public let completesNeeded : Int @objc public let rewardAmount : Int @objc public let status : String? } ``` ### Displaying a placement Placements are locations and moments inside the game when content can be shown. To show content for a placement, you'll need to specify a placement `tag`. Note that the show content calls are wrapped in a `canShowContent` check. This is to ensure that the placement is ready to be shown. If the placement is not ready, the SDK will return `false`. This helps guard against showing the user something that is not ready to be shown yet. `canShowContent` accepts an error block. It is optional in Swift; in Objective-C you must pass a block or `nil`. If there is an error while showing a placement, it will be returned in the completion handler. The error will contain a code and a description. Placement tags are listed on your app's **Manage** tab in the [Publisher Dashboard](https://www.tapresearch.com/supplier_dashboard/overview). ```swift title="ViewController.swift" let canShow: Bool = TapResearch.canShowContent(forPlacement: placementTag) { (error: NSError?) in // Optional: handle the error } if canShow { let customParameters: [String: Any] = ["param1": 123, "param2": "abc"] TapResearch.showContent(forPlacement: placementTag, delegate: self, customParameters: customParameters) { (error: NSError?) in if let error = error { print("\(error.code) \(error.localizedDescription)") } } } ``` ```swift title="ContentView.swift" if TapResearch.canShowContent(forPlacement: placementTag) { let customParameters: [String: Any] = ["param1": 123, "param2": "abc"] TapResearch.showContent(forPlacement: placementTag, delegate: self.tapResearchDelegates, customParameters: customParameters) } else { print("Placement \(placementTag) not ready") } ``` ```objectivec title="ViewController.m" BOOL canShow = [TapResearch canShowContentForPlacement:placementTag error:^(NSError * _Nullable error) { // Optional: handle the error }]; if (canShow) { [TapResearch showContentForPlacement:placementTag delegate:self completion:^(NSError * _Nullable error) { if (error) { NSLog(@"Error on showContent: %ld, %@", (long)error.code, error.localizedDescription); } }]; } ``` ### Passing custom parameters Custom parameters allow you to receive additional information about the user when they complete a survey. This can be used to filter out users who have already completed a survey, or to target specific users. These params will be returned in your [server-to-server postbacks](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/handling-rewards#server-to-server-callbacks). There are a maximum of 5 custom parameters that can be passed per placement. The below code is a zoomed-in view of the code above. :::note Parameters can only be ASCII characters; Unicode is not supported. Values must be strings, numbers, or booleans. ::: ```swift let customParameters: [String: Any] = ["param1": 123, "param2": "abc"] TapResearch.showContent(forPlacement: placementTag, delegate: self, customParameters: customParameters) { (error: NSError?) in if let error = error { print("Error \(error.code) \(error.localizedDescription)") } } ``` ```objectivec title="ViewController.m" [TapResearch showContentForPlacement:placementTag delegate:self customParameters:@{@"custom_param_1": @"test text", @"custom_param_2": @12} completion:^(NSError * _Nullable error) { if (error) { NSLog(@"Error on showContent: %ld, %@", (long)error.code, error.localizedDescription); } }]; ``` ### Granting boosts You can grant a boost to a user with the `grantBoost` function using Boosts you have set up for your app. First implement the `TapResearchGrantBoostResponseDelegate` to receive the result of granting a boost: ```swift func onTapResearchGrantBoostResponse(_ response: TapResearchSDK.TRGrantBoostResponse) { if response.success { // Perhaps update display in response to a successful boost } else { if let error = response.error { // Handle the error } } } ``` Grant a boost: ```swift // Assuming self implements TapResearchGrantBoostResponseDelegate TapResearch.grantBoost("BOOST_TAG", delegate: self) { (error: NSError?) in // Handle any error } ``` First implement the `TapResearchGrantBoostResponseDelegate` to receive the result of granting a boost: ```objectivec - (void)onTapResearchGrantBoostResponse:(TRGrantBoostResponse * _Nonnull)response { if (response.success) { // Perhaps update display to indicate boost granted } else { if (response.error) { // Handle the error } } } ``` Grant a boost: ```objectivec // Assuming self implements TapResearchGrantBoostResponseDelegate [TapResearch grantBoost:@"YOUR_BOOST_TAG" delegate:self errorHandler:^(NSError * _Nullable error) { // Handle any error }]; ``` #### The `TRGrantBoostResponse` object: ```swift @objc public final class TRGrantBoostResponse : NSObject, Encodable { @objc public let boostTag : String @objc public let success : Bool @objc public let error : NSError? } ``` ## NotificationCenter events Available from SDK `3.8.0--rc0`. Instead of implementing a delegate method for some callbacks, you can observe a notification on the default `NotificationCenter`. | Notification name | Posted when | Replaces | |---|---|---| | `TapResearch.TapResearchSDKReady` | The SDK is ready to be used | `onTapResearchSdkReady` (`TapResearchSDKDelegate`) | | `TapResearch.TapResearchDidError` | An error occurs | `onTapResearchDidError` (`TapResearchSDKDelegate`) | | `TapResearch.TapResearchContentShown` | TapResearch content is shown | `onTapResearchContentShown` (`TapResearchContentDelegate`) | | `TapResearch.TapResearchContentDismissed` | TapResearch content is dismissed | `onTapResearchContentDismissed` (`TapResearchContentDelegate`) | The error and content notifications carry a value in `userInfo`: | `userInfo` key | Value | |---|---| | `TapResearch.ErrorKey` | The `NSError`, on `TapResearchDidError` | | `TapResearch.PlacementTagKey` | The placement tag `String`, on `TapResearchContentShown` and `TapResearchContentDismissed` | To register, add an observer for each notification you need, for example `TapResearch.TapResearchContentShown`: ```swift func registerForNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(handleTapResearchNotification(_:)), name: TapResearch.TapResearchContentShown, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleTapResearchNotification(_:)), name: TapResearch.TapResearchDidError, object: nil) } @objc func handleTapResearchNotification(_ notification: Notification) { if let placementTag = notification.userInfo?[TapResearch.PlacementTagKey] as? String { // Content shown (or dismissed) for placementTag } if let error = notification.userInfo?[TapResearch.ErrorKey] as? NSError { // Handle the error } } ``` ## Need help? If you're experiencing issues or need assistance, reach out to [developers@tapresearch.com](mailto:developers@tapresearch.com). --- **Stay updated:** watch the [TapResearch iOS SDK on GitHub](https://github.com/TapResearch/TapResearch-iOS-SDK) to get notified about new releases. --- # iOS Native Survey Tiles Source: https://supply-docs.tapresearch.com/docs/3.x/survey-wall-preview/ios-surveys :::info Test mode If your app is in test mode, you **must** use a test user. Add test users in the [Publisher Dashboard](https://www.tapresearch.com/supplier_dashboard/overview) under **More → Test devices**. ::: ## Installation Start with the [iOS integration guide](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/ios) if you haven't set up the SDK yet. See the [Native Survey Tiles example app](https://github.com/TapResearch/demo-apps/tree/master/ios/BasicDemos/SurveyWallPreview) on GitHub. ### Before you begin * You must be on SDK v3.4.2+ to have access to Native Survey Tiles. * The wall preview feature needs to be enabled and set up by the TapResearch team so please reach out to your account manager when you are ready to get started * Native Survey Tiles should be on a dedicated placement, separate from the standard Survey Wall (if applicable) * **Always wait** until the SDK is ready (via the `onTapResearchSdkReady` callback or by checking `TapResearch.isReady()`) before calling any Native Survey Tiles interfaces * Set a `TapResearchSurveysDelegate` (its `onTapResearchSurveysRefreshed(forPlacement:)` method) before calling `getSurveys` or `showSurvey`, so your app hears when the surveys change. :::info Support Any other questions? Reach out to your account manager or via Slack and we'll be happy to help! ::: ## Introduction **Native Survey Tiles** (formerly *Survey Wall Preview*) let you provide users with available surveys, directly inside your app. Some benefits of this include: * **Custom UI** — Create your own UI presentation with survey tiles/cards * **Direct survey access** — Provide users with direct entry into surveys they choose --- ### Key considerations & UI design When designing your survey tiles/cards, consider these elements: ### 1. The profile survey New users must complete the introductory profile survey before they can access other surveys. For these new users, the SDK will return **only** this survey until they have completed it. * Only shown to users that are new to TapResearch * Will always be returned by itself, with a survey identifier of `profile` * Display example: ### 2. Survey details After completing the profile survey, users should then start receiving real surveys. Surveys will have the following attributes: ```swift @objc public final class TRSurvey : NSObject, Codable { // Primary attributes @objc public let surveyIdentifier : String // Unique identifier, will be used when a user taps on a survey @objc public let lengthInMinutes : Int // The estimated time to complete the survey @objc public let rewardAmount : Double // The reward amount for taking the survey @objc public let currencyName : String // The name of the reward currency @objc public let isHotTile : Bool // Whether the survey should be designated as a "hot tile" @objc public let category : String? // The survey's category, if it has one // Sale attributes @objc public let isSale : Bool // Whether a currency sale is currently active @objc public let saleMultiplier : Double // The multiplier being applied to the sale @objc public let saleEndDate : String? // If a sale is active, the UTC date it will end @objc public let preSaleRewardAmount : Double // The pre-multiplier reward amount, for enhancing UI during a sale } ``` * We recommend displaying all primary data points to allow users to choose which survey length/reward they want * Display example: ### 3. "Hot" tiles Hot tiles are surveys with exceptional scores, typically offering the best time-to-reward ratio. Displaying a special UI highlight for these surveys is recommended, as they tend to increase user engagement and click-through rates. * Display example: ### 4. Currency Sales When running promotional currency sales, the relevant sale attributes of the survey object will populate, allowing you to show enhanced UIs and CTAs to users. We recommend using this data to display the extra rewards boost on the individual tiles. * Display example: --- ## Integration ### SDK interfaces #### Checking for available surveys When you have received notification that the SDK is ready (see [Checking if the SDK is ready](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/ios#checking-if-the-sdk-is-ready)) you should first check if there are surveys available for your placement: ```swift let hasSurveys: Bool = TapResearch.hasSurveys(for: placementTag) { (error: NSError?) in // Optional: handle the error } ``` ```objectivec BOOL hasSurveys = [TapResearch hasSurveysFor:placementTag errorHandler:^(NSError * _Nullable error) { // Optional: handle the error }]; ``` #### Getting available surveys Get the surveys for your placement. Note: Fetch surveys only after receiving the SDK Ready callback. ```swift let surveys: [TRSurvey] = TapResearch.getSurveys(for: placementTag) ``` ```objectivec NSArray *surveys = [TapResearch getSurveysFor:placementTag errorHandler:nil]; ``` #### Check that a survey can be shown Before showing, it is always best to check if the survey can be shown using `canShowSurvey`: ```swift let canShow: Bool = TapResearch.canShowSurvey(surveyId: survey.surveyIdentifier, forPlacementTag: placementTag) ``` ```objectivec BOOL canShow = [TapResearch canShowSurveyWithSurveyId:survey.surveyIdentifier forPlacementTag:placementTag]; ``` #### Showing a survey Showing a survey works similarly to `showContent` used for showing TapResearch survey content: after checking if a survey can be shown, call `showSurvey` with a survey ID, placement tag and a content delegate to receive `onTapResearchContentShown` and `onTapResearchContentDismissed` callbacks, see [TapResearchContentDelegate](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/ios#tapresearchcontentdelegate) for details. ```swift TapResearch.showSurvey(surveyId: survey.surveyIdentifier, placementTag: placementTag, delegate: self) { (error: NSError?) in // Handle the error } ``` ```objectivec [TapResearch showSurveyWithSurveyId:survey.surveyIdentifier placementTag:placementTag delegate:self errorHandler:^(NSError * _Nullable error) { // Handle the error }]; ``` If you need to pass custom parameters use: ```swift TapResearch.showSurvey(surveyId: survey.surveyIdentifier, placementTag: placementTag, delegate: self, customParameters: ["param1": 123, "param2": "abc"]) { (error: NSError?) in // Handle the error } ``` ```objectivec [TapResearch showSurveyWithSurveyId:survey.surveyIdentifier placementTag:placementTag delegate:self customParameters:@{@"param1": @123, @"param2": @"abc"} errorHandler:^(NSError * _Nullable error) { // Handle the error }]; ``` ### Callback Native Survey Tiles adds a callback that lets you know when surveys have been refreshed. #### Setting the delegate Set the delegate using `setSurveysDelegate` before calling `getSurveys` or `showSurvey`. Without it, your app isn't told when the surveys for a placement change. ```swift TapResearch.setSurveysDelegate(self) ``` ```objectivec [TapResearch setSurveysDelegate:self]; ``` To remove the delegate call the `setSurveysDelegate` with `nil`. #### Handling the callback You will see calls to the callback function when surveys have been completed, after any TapResearch content has been dismissed. Make sure the delegate object implements `TapResearchSurveysDelegate` and updates local storage and displays with the updated surveys: ```swift func onTapResearchSurveysRefreshed(forPlacement placementTag: String) { let surveys: [TRSurvey] = TapResearch.getSurveys(for: placementTag) // Update your survey tiles } ``` ```objectivec - (void)onTapResearchSurveysRefreshedForPlacement:(NSString *)placementTag { NSArray *surveys = [TapResearch getSurveysFor:placementTag errorHandler:nil]; // Update your survey tiles } ``` --- # iOS orientation handling Source: https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/ios-alternate-orientation-handling It's important that landscape apps not lock the screen rotation when rendering TapResearch. Landscape orientation within the TapResearch experience would result in degraded engagement and revenue performance. By contrast, apps that allow rotation to portrait mode for TapResearch screens typically achieve twice the earnings of apps that are locked in landscape. For the cross-platform guidance that applies to every SDK platform, see [Screen Orientation](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/screen-orientation). ## Alternate orientation handling If you are in a situation where enabling portrait for iPhone is not possible in Xcode's project settings you can use this alternate method for allowing portrait for the TapResearch iOS SDK. **This assumes you are not using a SceneDelegate.** ## 1. Set allowed orientations. In the Xcode project editor's "General" tab set the required orientations in the "Deployment Info" section. ## 2. Add an iPhone check helper function. We only need to make sure that portrait is available for iPhone, add this simple helper function to your AppDelegate: ```objectivec - (BOOL)isPhone { return ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone); } ``` ```swift var isPhone: Bool { return UIDevice.current.userInterfaceIdiom == .phone } ``` ## 3. Add supported orientation function to AppDelegate ### 3.1. Add a boolean flag for allowing orientations Add a boolean property to AppDelegate: ```objectivec @property (nonatomic, assign) BOOL allowAllOrientations; ``` ```swift var allowAllOrientations: Bool = false ``` ### 3.2. Set boolean to NO/false If using Objective-C, inside `application:didFinishLaunchingWithOptions:` as soon as the function is entered set the boolean to NO. If using Swift make this part of the variable definition (as seen in 3.1 above). ### 3.3. Add supported orientations function to AppDelegate ```objectivec - (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { if ([self isPhone]) { if (self.allowAllOrientations) { // App supports all except upside-down return UIInterfaceOrientationMaskAllButUpsideDown; } else { // Initial launch screen supports only Landscape return UIInterfaceOrientationMaskLandscape; } } else { // iPad return UIInterfaceOrientationMaskAll; } } ``` ```swift func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { if isPhone { if allowAllOrientations { return [.allButUpsideDown] } else { return [.landscape] } } else { // iPad return [.all] } } ``` ### 3.4. Set boolean flag to YES When you are ready to allow portrait set the boolean to `YES` (or `true` in Swift). ## 4. LaunchScreen.storyboard If you are using a LaunchScreen.storyboard make sure it is a basic UIViewController without any outlet connections, no view controller subclass is needed for this. ## 5. Using SceneDelegate If you are using a SceneDelegate, you can also return supported orientations per view controller: ```objectivec - (UIInterfaceOrientationMask)supportedInterfaceOrientations { // For example: return UIInterfaceOrientationMaskLandscape; } ``` ```swift override var supportedInterfaceOrientations: UIInterfaceOrientationMask { // For example: return .landscape } ``` You can do this globally and just let your root view controller report available orientations. --- # SDK overview Source: https://supply-docs.tapresearch.com/docs/3.x/basic-integration/integration-options The TapResearch SDK is the fastest way to add surveys to a native app. It handles survey retrieval, ranking, eligibility, profiling, and reward callbacks for you. :::tip Creating your app In the [Publisher Dashboard](https://www.tapresearch.com/supplier_dashboard/overview), create a new app and select **SDK**, then the platforms you'll ship on (iOS, Android, or both). See the [Setup checklist](https://supply-docs.tapresearch.com/docs/3.x/setup) for the full flow. ::: There are **two ways to present surveys** with the SDK — use either, or both together. Survey wall (standard) Add a call-to-action — a button, banner, or menu item. When the user taps it, TapResearch opens the full-screen survey wall in a web view and takes over. The quickest path: one entry point, and we handle the whole experience. Native Survey Tiles The SDK returns an array of the surveys a user qualifies for, so you render them as native tiles in your own UI — reward amount, estimated time, and all. The user taps a tile and that survey launches directly. You can mix the two — for example, surface a few preview tiles in your feed and a CTA into the full wall elsewhere. :::info Platform guides [iOS](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/ios) · [Android](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/android) · [React Native](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/react-native) · [Unity](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/unity) · [Flutter](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/flutter) ::: ## What the SDK handles for you - **Profiling & targeting** — users are matched to surveys by demographics and eligibility automatically. - **Quick Questions** — short, in-app questions you can ask your own users; only available through the SDK. See [Quick Questions](https://supply-docs.tapresearch.com/docs/3.x/3.2-only/quick-question-how-to). - **Survey ranking, eligibility filtering, and reward callbacks** — handled for you, so integration stays light. :::tip Want a fully custom, server-side experience? If you'd rather fetch surveys from your backend and render everything in your own UI without the SDK, use the [Survey Feed API](https://supply-docs.tapresearch.com/docs/3.x/survey-feed-api/overview) instead. ::: --- # Integrate with AI Source: https://supply-docs.tapresearch.com/docs/3.x/basic-integration/integrate-with-ai Prefer to let an AI coding agent do the heavy lifting? Pick your platform and copy the prompt below into Claude, ChatGPT, Cursor, Codex — whatever you use. It points the agent at our full, always-current SDK reference for that platform, so it builds from the real documentation instead of guessing. Your agent can scaffold initialization, reward callbacks, and placement display from there. You stay in control — review what it writes, and dive into the rest of these docs whenever you want the details yourself. ## After you integrate: verify it's working Once the code is in place, run through these checks on a **test device**. **Your AI agent can help** — it can write a smoke test, walk you through each step, and debug failures. What it *can't* do is see your account, so your app's **Integration** tab in the [Publisher Dashboard](https://www.tapresearch.com/supplier_dashboard/overview) is what confirms each step actually passed — it detects each one from real activity and marks it done. :::tip Use a real test session These checks only register from a real test user reaching the SDK — firing a test postback on its own won't complete them. Add a test device first (**More → Test devices**); only test users can initialize the SDK before go-live. ::: 1. **SDK initialization received** — Initialize the SDK with your app's API token. The Integration tab marks this once it sees your first session. 2. **Enter survey wall from app** — Show a placement and reach the survey wall. (You'll need a placement with content configured on the **Manage** tab first.) 3. **Reward callback configured** — Set a server-to-server postback URL (this auto-completes), or implement the in-app reward handler. 4. **Generate test survey complete** — Complete a test survey so a completion is recorded against your app. 5. **Reward redeemed for test user** — Confirm your postback handler or in-app reward callback redeems the reward for the test user. If a step doesn't check off, it's the fastest signal of where the integration broke. For deeper testing guidance, see [Testing & QA](https://supply-docs.tapresearch.com/docs/3.x/testing-and-qa). --- # Quick Question how-to Source: https://supply-docs.tapresearch.com/docs/3.x/3.2-only/quick-question-how-to Quick Questions allow you to ask up to **three questions** to your users at any point in your app. Currently available question types include: * Multiple choice (single-select or multi-select) * Open-ended text responses Follow the steps below to set up your first Quick Question: ## Step 1: Create a currency If you haven't already, [create a currency](https://supply-docs.tapresearch.com/docs/3.x/setup#add-a-currency) for rewarding users. ## Step 2: Create a placement Ensure you have a placement created for where the Quick Question will appear. A placement defines the physical location in your app (e.g., home screen, earn center). **Important:** Quick Questions must be attached to a placement whose **Placement type** is **"Pop-up"**, not "Survey wall". Unlike survey walls, Quick Questions are triggered automatically to users matching your targeting criteria—they don't require a button click. ## Step 3: Create your Quick Question content Once your placement is ready: 1. Click the **Create content** button in the upper right corner 2. Select **"Quick Questions"** ## Step 4: Build your questions In the content builder: 1. Choose your question type (multiple choice single-select, multiple choice multi-select, or open text) 2. Fill in the required fields 3. Add up to **3 questions** per Quick Question content ### Question guidelines **Multiple Choice Questions:** * No character limit on questions or answers, but check the preview to ensure readability * No limit on answer options, but consider user experience (more options = more scrolling) * **Best practice:** Keep answer options to 7 or fewer for optimal data quality * Use the randomize toggle to avoid order bias and maintain data integrity **Open-Ended Questions:** * Answers are limited to **250 characters** ## Step 5: Configure display settings Once your questions are composed: 1. Navigate to the **"Configure"** tab 2. Choose the platform(s) (iOS, Android, etc.) 3. Select the placement where the Quick Question will be shown ## Step 6: Set up rewards Determine whether to reward users for answering the Quick Question, and if so, specify the reward amount. ## Step 7: Add Survey Wall link (optional) Choose whether to include a link to the TapResearch survey wall at the end of the Quick Question. This allows users to continue to more survey opportunities. **Note:** * You can select any currency that has an associated survey wall in your app * The currency can differ from the one used for Quick Question rewards ## Step 8: Configure response settings Set your response limits: * Cap the number of participants * Set an end date/time for the Quick Question ## Step 9: Define target audience Specify which users will see this Quick Question based on their attributes. **Learn more:** For detailed information about user attributes and targeting, see our [User Attributes and Targeting documentation](https://supply-docs.tapresearch.com/docs/3.x/operational-tools/user-attributes). ## Step 10: Launch your Quick Question Once all steps are complete: 1. Click **"Launch Quick Question"** in the upper right corner 2. Your Quick Question will go live and responses will start coming in! --- **Need help?** Contact developers@tapresearch.com or your Account Manager for additional support. --- # Handling Quick Question responses Source: https://supply-docs.tapresearch.com/docs/3.x/3.2-only/handling-quick-question-responses ## Overview There are several ways to ingest Quick Question responses: * **In-app callback** - Real-time responses within your app * **Server-to-server postback** - Automated server notifications * **CSV download** - Manual export from the dashboard * **API download** - Programmatic data retrieval Select an approach based on how you plan to use the Quick Question response data. ## In-app callback In-app callbacks are fired whenever a user completes a Quick Question. **Use this method when you need real-time access to response data.** The Quick Question callback is registered differently on each platform. See the platform-specific documentation below for implementation details: * [iOS Quick Question response](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/ios#quick-question-response) * [Android Quick Question response](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/android#quick-question-callback-setup-additional-information) * [Unity Quick Question response](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/unity#quick-question-response-callback) * [React Native Quick Question response](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/react-native#quick-question-response) * [Flutter Quick Question response](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/flutter#quick-questions) ## Server-to-server postback Server-to-server postbacks are sent after a user answers a Quick Question, if a postback URL is configured in your app settings. **Note:** Setting up a postback URL does not prevent in-app callbacks from firing—both can be used simultaneously. ### Setup instructions 1. In the [Publisher Dashboard](https://www.tapresearch.com/supplier_dashboard/overview), open your app title and click **Settings** 2. Select the platform (iOS and Android are configured separately) 3. Add your Quick Question postback endpoint to **"Quick Questions data postback URL"** 4. Click **"Test data postback"** to verify the endpoint 5. Click **"Save changes"** **Important:** You must receive a 200 response from the test postback to save the URL. ### Request format Quick Question postbacks use `GET` requests with URL-encoded, nested query parameters and a `sig` signature. Validate them as described in [Handling rewards](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/handling-rewards#signature-validation). ### Example payload The following JSON illustrates the payload fields before query-string encoding: ```json { "survey_identifier": "YOUR_SURVEY_IDENTIFIER", "app_name": "YOUR_APP_NAME", "api_token": "YOUR_API_TOKEN", "sdk_version": "3.5.3", "platform": "Android", "placement_tag": "YOUR_PLACEMENT_TAG", "user_identifier": "YOUR_USER_IDENTIFIER", "user_locale": "en", "seen_at": "2025-10-13T22:31:12.455Z", "complete": { "complete_identifier": "tap_qq_68_fb67345f15e08892a0635b7ddcac3138", "completed_at": "2025-10-13T22:31:24.869Z" }, "questions": [ { "question_identifier": "50e2ed203cd2b810ba982b7ce9841939", "question_text": "This is the question", "question_type": "multiple_choice__single", "user_answer": { "value": "Answer F", "identifiers": [ "78bf19eaad5a8bef5c804db7f8760f58" ] } }, { "question_identifier": "e2b3f38f2c5f423ed8303bd68dc2dc77", "question_text": "Test", "question_type": "open_text", "user_answer": { "identifiers": [], "value": "My answer" } } ], "target_audience": [ { "filter_attribute_name": "some_attribute_name", "filter_operator": "equals", "filter_value": "SomeValue", "user_value": "SomeValue" } ] } ``` ## CSV download CSV download is available for any Quick Question through the publisher dashboard. **To download:** 1. Click the **"..."** dropdown in the top right corner of your Quick Question content card 2. Select **"Download CSV"** The CSV file contains all current responses and is updated in real-time. ## API download API download is available for all Quick Questions. **This method is ideal when:** * Quick Question data is not needed immediately * You want to pull all response data on a scheduled basis * You're ingesting data into your own data warehouse **Note:** This data is updated on a daily basis. ### Getting started See the [Reporting API Documentation](https://supply-docs.tapresearch.com/docs/3.x/operational-tools/reporting-api#quick-question-results) for implementation details. To get access to the stats API, contact our account management team at [developers@tapresearch.com](mailto:developers@tapresearch.com). --- # Screen orientation Source: https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/screen-orientation **Critical for landscape apps:** Do not lock screen rotation when displaying TapResearch content. ## Why this matters * **Landscape-locked apps** experience degraded engagement and revenue performance * **Apps allowing portrait rotation** for TapResearch typically achieve **2x the earnings** of landscape-locked apps ## Implementation Allow your app to rotate to portrait mode when displaying TapResearch screens for optimal performance. * **iOS developers:** See [iOS Orientation Handling](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/ios-alternate-orientation-handling) for how to allow portrait for TapResearch content when the rest of your app is landscape. * **Unity developers:** See the [screen orientation guide](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/unity#screen-orientation-for-landscape-applications) for platform-specific instructions. --- # Handling rewards Source: https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/handling-rewards ## Overview **There are two ways to receive rewards** (choose one per app): * **In-app callbacks** - Default method * **Server-to-server postbacks** - Requires a postback URL. Setting one switches the app from in-app callbacks to postbacks. ### Reward flow ## In-app callbacks In-app callbacks deliver a list of rewards through your SDK's reward callback. **Example:** If a user completes three surveys, the SDK fires one callback containing all three rewards. **Key features:** * TapResearch notifies users of their rewards * Default reward method: used unless you set a postback URL **When callbacks fire:** * When the user closes TapResearch * After successful SDK initialization, to deliver unredeemed rewards :::info Setting a postback URL switches the app from in-app callbacks to server-to-server postbacks. ::: ## Server-to-server postbacks The server-to-server postback is a `GET` request that TapResearch sends to your postback URL as soon as a user earns a reward. The reward details are passed as query parameters, and an HMAC-MD5 signature (`sig`) lets you verify the request came from TapResearch. **Important:** With server-to-server postbacks your app is responsible for notifying users of the rewards they receive — TapResearch does not notify users with this method. ### Set your postback URL In the [Publisher Dashboard](https://www.tapresearch.com/supplier_dashboard/overview), open your app's **Settings** tab and select **iOS settings or Android settings**. Enter your URL in **Rewards/monetization postback URL** under **Server-to-server postbacks**. **URL requirements:** * Must begin with `https://` * No spaces or special characters, other than the placeholders described in [Renaming parameters](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/handling-rewards#renaming-parameters) * Must respond within 5 seconds. The dashboard test requires HTTP `200`; live postbacks accept any `2xx` response. ### Testing your postback URL Run **Test rewards postback** before saving or updating the URL. The test must return HTTP `200` before the dashboard allows you to save. ### Sample requests ```text https://your-postback-url.example.com/postback?api_token=your-api-token&cpid=tap_37939e4ede350f3a8d5149d2fcaa025e&ip_address=203.0.113.42&offer_identifier=8f14e45fceea167a5a36dedd4bea2543&payout_amount=191&payout_currency=gold&payout_type=3&revenue=0.5&tid=777ca23551a4a9173920c22e1ed7f4f3&uid=developers%40tapresearch.com&sig=435ad87fb971836540ebc3a320efe9f1 ``` **POST requests** To receive postbacks as `POST` requests, contact [developers@tapresearch.com](mailto:developers@tapresearch.com). The fields are sent in a JSON body, with `sech` instead of `sig` for signature validation. ```json { "tid": "777ca23551a4a9173920c22e1ed7f4f3", "api_token": "your-api-token", "cpid": "tap_37939e4ede350f3a8d5149d2fcaa025e", "revenue": "0.5", "payout_amount": 191, "payout_currency": "gold", "uid": "developers@tapresearch.com", "did": "0258DE71-DFEB-4399-BF26-11C1F6E600D2", "payout_type": 3, "offer_identifier": "8f14e45fceea167a5a36dedd4bea2543", "ip_address": "203.0.113.42", "sech": "7cf1c6a66c67c596280437985a76ccea4d78705116b9473be79acf640596a630" } ``` ### Parameters | Parameter | Type | Description | |-----------|------|-------------| | `api_token` | String | Your app's API token. | | `cpid` | String | Unique identifier for the reward. Use it to ensure each reward is credited only once. | | `did` | String | Device identifier, if available. | | `ip_address` | String | The user's IP address, if available. | | `offer_identifier` | String | Identifier of the TapResearch offer that issued the reward. | | `payout_amount` | Integer | Amount of currency earned by this user. | | `payout_currency` | String | The name of the currency the user earned. | | `payout_type` | Integer | The action that the user was rewarded for. 0 - Profile Complete, 3 - Survey Rewarded, 9 - Quick Question Completed (SDK only), 10 - Bonus Bar Reward. | | `revenue` | Decimal | Amount you will be paid for this reward, in USD. | | `tid` | String | Transaction ID (click ID) of the user's session. Use `cpid`, not `tid`, to identify a reward. | | `uid` | String | Persistent unique identifier for this user. | | `sig` | String | `GET` requests only, always the last parameter: an HMAC-MD5 of the query string before it. See [Signature validation](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/handling-rewards#signature-validation). | :::note Postbacks may include additional fields. Validate the signature against the entire query string you receive, not a fixed list of fields. ::: ### Renaming parameters If your postback URL points at a tracking or affiliate network that expects its own parameter names, put placeholders in the URL's query string. TapResearch fills each placeholder with the matching value and sends that value only under your parameter name. | Placeholder | Filled with | |-------------|-------------| | `{UID}` | `uid` | | `{DID}` | `did` | | `{TID}` | `tid` | | `{CPID}` | `cpid` | | `{API_TOKEN}` | `api_token` | | `{PAYOUT_AMOUNT}` | `payout_amount` | | `{PAYOUT_CURRENCY}` | `payout_currency` | | `{REVENUE}` | `revenue` | | `{PAYOUT_TYPE}` | `payout_type` | | `{IP_ADDRESS}` | `ip_address` | **Postback URL you save:** ```text https://your-postback-url.example.com/postback?clickid={TID}&sum={REVENUE}&goal={PAYOUT_TYPE}&custom_field2={PAYOUT_AMOUNT} ``` **Request you receive:** ```text https://your-postback-url.example.com/postback?clickid=777ca23551a4a9173920c22e1ed7f4f3&sum=0.5&goal=3&custom_field2=191&api_token=your-api-token&cpid=tap_37939e4ede350f3a8d5149d2fcaa025e&ip_address=203.0.113.42&offer_identifier=8f14e45fceea167a5a36dedd4bea2543&payout_currency=gold&uid=developers%40tapresearch.com&sig=a86c2ce25c178aa375b82e0d3b51e93a ``` **How placeholders work:** * Placeholders are case-sensitive and go in parameter values. * Parameters you don't rename are still sent under their standard names. * Parameters with unknown placeholders, literal braces, or unavailable values are omitted. * Placeholders apply to `GET` postbacks only. `sig` remains the last parameter and covers the entire query string. Don't name a custom parameter `sig`. See [Signature validation](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/handling-rewards#signature-validation). Use **Test rewards postback** to try a URL with placeholders before you save it. ### Security `GET` postbacks are signed with `sig`, as described below. #### Signature validation Every `GET` postback ends with a `sig` parameter: an HMAC-MD5 of the query string that comes before it. Validate it on every request before you reward a user. **Sign the entire query string exactly as you receive it, minus `sig` — don't rebuild it from a fixed list of parameters.** The signature covers every parameter present, including your own static and renamed parameters, so hashing whatever arrives (as the steps and code below do) stays correct as parameters are added. Use your app's **API Secret**, available in its settings in the [Publisher Dashboard](https://www.tapresearch.com/supplier_dashboard/overview). The examples use the sample secret `26dcc0fc7b6208fdfeffaf19f627cb4a`. 1. Start with the incoming postback request, for example: ```text https://your-postback-url.example.com/postback?api_token=your-api-token&cpid=tap_37939e4ede350f3a8d5149d2fcaa025e&ip_address=203.0.113.42&offer_identifier=8f14e45fceea167a5a36dedd4bea2543&payout_amount=191&payout_currency=gold&payout_type=3&revenue=0.5&tid=777ca23551a4a9173920c22e1ed7f4f3&uid=developers%40tapresearch.com&sig=435ad87fb971836540ebc3a320efe9f1 ``` 2. Isolate the query string: everything after the `?`. 3. Remove `&sig=` and the signature after it. `sig` is always the last parameter. 4. Percent-decode the rest, preserving literal `+` characters. The examples below use decoders that do this. 5. Run your API secret and the decoded query string through an HMAC-MD5 generator, with lowercase hex output. 6. Compare your result with the `sig` value, using a constant-time comparison. If they match, record the reward and credit the user. ```ruby require "openssl" require "uri" # Sample request URL (in Rails, read the raw query with request.query_string) url = "https://your-postback-url.example.com/postback?api_token=your-api-token&cpid=tap_37939e4ede350f3a8d5149d2fcaa025e&ip_address=203.0.113.42&offer_identifier=8f14e45fceea167a5a36dedd4bea2543&payout_amount=191&payout_currency=gold&payout_type=3&revenue=0.5&tid=777ca23551a4a9173920c22e1ed7f4f3&uid=developers%40tapresearch.com&sig=435ad87fb971836540ebc3a320efe9f1" # Isolate the query string and split off sig, which is always last query_string = url.split("?", 2).last signature = query_string[/&sig=([0-9a-f]+)\z/, 1] unsigned_query = query_string.sub(/&sig=[0-9a-f]+\z/, "") # Percent-decode only: "+" stays "+" decoded = URI::Parser.new.unescape(unsigned_query) # Generate HMAC-MD5 api_secret = "26dcc0fc7b6208fdfeffaf19f627cb4a" expected = OpenSSL::HMAC.hexdigest("MD5", api_secret, decoded) puts OpenSSL.secure_compare(expected, signature) # true ``` ```php ``` ```java private static final String API_SECRET = "26dcc0fc7b6208fdfeffaf19f627cb4a"; private static final String ALGO = "HmacMD5"; try { // Sample request URL (in a servlet, read the raw query with request.getQueryString()) String urlString = "https://your-postback-url.example.com/postback?api_token=your-api-token&cpid=tap_37939e4ede350f3a8d5149d2fcaa025e&ip_address=203.0.113.42&offer_identifier=8f14e45fceea167a5a36dedd4bea2543&payout_amount=191&payout_currency=gold&payout_type=3&revenue=0.5&tid=777ca23551a4a9173920c22e1ed7f4f3&uid=developers%40tapresearch.com&sig=435ad87fb971836540ebc3a320efe9f1"; // Isolate the query string and split off sig, which is always last String queryString = urlString.substring(urlString.indexOf('?') + 1); int sigIndex = queryString.lastIndexOf("&sig="); String signature = queryString.substring(sigIndex + "&sig=".length()); String unsignedQuery = queryString.substring(0, sigIndex); // Percent-decode only: protect "+" so URLDecoder doesn't turn it into a space String decoded = URLDecoder.decode(unsignedQuery.replace("+", "%2B"), StandardCharsets.UTF_8); // Generate HMAC-MD5 Mac mac = Mac.getInstance(ALGO); mac.init(new SecretKeySpec(API_SECRET.getBytes(StandardCharsets.UTF_8), ALGO)); byte[] bytes = mac.doFinal(decoded.getBytes(StandardCharsets.UTF_8)); StringBuilder expected = new StringBuilder(); for (byte b : bytes) { expected.append(String.format("%02x", b)); } System.out.println(MessageDigest.isEqual( expected.toString().getBytes(StandardCharsets.UTF_8), signature.getBytes(StandardCharsets.UTF_8))); // true } catch (Exception e) { e.printStackTrace(); } ``` #### IP allowlist To further harden your endpoint, you can restrict incoming postback requests to the following TapResearch source IP addresses: | IP Address | |------------| | 34.198.225.203 | | 3.88.121.21 | | 3.89.214.250 | | 3.92.129.242 | ### Retries If a postback fails, our system retries sending the reward for 48 hours OR until a `2xx` response code is received. --- # TRReward Source: https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/tr-reward The reward object the SDK returns when a user earns a reward. Your reward callback receives a list of them. The iOS and Android SDKs use slightly different names and types for some properties, shown below. ## Properties | Property | iOS | Android | Description | |---|---|---|---| | Transaction identifier | `transactionIdentifier` (String?) | `transactionIdentifier` (String?) | Unique identifier for the transaction. Use it to deduplicate rewards in your app or in your [server-to-server postback](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/handling-rewards#server-to-server-callbacks) handling. | | Placement tag | `placementTag` (String?) | `placementTag` (String?) | The placement tag where the reward was earned. | | Placement identifier | `placementIdentifier` (String?) | `placementIdentifier` (String?) | The placement identifier where the reward was earned. | | Currency name | `currencyName` (String?) | `currencyName` (String?) | Name of the rewarded currency. **Note:** This is the **Currency name** set in the Publisher Dashboard, not the **Display name**. | | Reward amount | `rewardAmount` (Int) | `rewardAmount` (Float?) | Amount of currency rewarded (in your app's currency). | | Payout event | `payoutEvent` (String?) | `payoutEventType` (String?) | Type of payout event — see [Payout event values](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/tr-reward#payout-event-values). | In Java, use the getters (`getRewardAmount()`, `getPayoutEventType()`, and so on). ## Payout event values | Event | iOS `payoutEvent` | Android `payoutEventType` | |---|---|---| | User completed the profiling flow | `profile_reward` | `PROFILE_REWARD` | | User started a survey but was disqualified | `partial_payout` | `PARTIAL_PAYOUT` | | User successfully completed a survey | `full_payout` | `FULL_PAYOUT` | | Quick Questions payout | `quick_questions_payout` | `QUICK_QUESTIONS_PAYOUT` | --- # SDK error codes Source: https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/sdk-error-codes When using the SDK, you may encounter the following error codes. On Android they arrive as a [`TRError`](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/tap-objects) `code`; on iOS as the `NSError` `code`. | Code | Description | |-------|---------------------------------------------------------------------------------| | 1000 | Invalid API token | | 1001 | Missing user identifier | | 1002 | Service unavailable | | 1003 | Missing header | | 1004 | Network timeout | | 1005 | Unknown network error | | 1006 | Javascript execution error | | 1007 | App unavailable | | 1008 | No internet connection | | 2000 | Missing required tag or invalid placement tag | | 2001 | No content available for this placement | | 3000 | Missing attribute | | 3001 | No configuration for landscape orientation while attempting to show in landscape | | 3002 | No configuration for portrait orientation while attempting to show in portrait | | 4000 | Invalid reward identifier | | 6000 | Not initialized | | 6001 | Missing API token | | 6002 | Unable to present UI | | 6003 | Unable to create UI | | 6004 | Unable to decode TRError JSON | | 6005 | Reward delegate was deallocated or not set | | 6006 | Bad or missing custom parameter | | 6007 | Missing application context | | 6008 | Missing placement tag | | 6009 | Missing content callback | | 6010 | SDK not ready | | 6011 | Unable to convert user attributes | | 6012 | Invalid survey Id for placement | | 6013 | No surveys for placement | | 6014 | Quick Questions data delegate was deallocated or not set | | 6015 | Invalid boost tag | | 6016 | Too many requests | | 6017 | Placement details missing | | 10000 | Invalid notification command | | 10001 | Notification missing placementTag while command is showContent | | 10002 | Notification missing scheduledDate and timeDelta, cannot schedule | ## Debugging To assist with debugging, please provide: * The error code you're encountering * A complete stack trace of the error * Any relevant context about when the error occurs Contact developers@tapresearch.com with this information for support. --- # Initialization options Source: https://supply-docs.tapresearch.com/docs/3.x/operational-tools/initialization-options You can pass user attributes when you initialize the SDK. On Android they go in a `TapInitOptions` object; on iOS they are parameters of `initialize`. ## Configuration options | Option | Description | Required? | |-----------------------------------------|------------------------------------------------------------------------------------------------|-----------| | `userAttributes` | User attributes; see [User attributes and targeting](https://supply-docs.tapresearch.com/docs/3.x/operational-tools/user-attributes) | No | | `clearPreviousAttributes` | Replaces previously sent attributes with this set (default `false`), see [below](https://supply-docs.tapresearch.com/docs/3.x/operational-tools/initialization-options#clearing-previous-attributes) | No | `initialize` takes an optional `initOptions` parameter of type `TapInitOptions`: ```kotlin data class TapInitOptions( val userAttributes: HashMap? = null, val clearPreviousAttributes: Boolean? = false, ) ``` See [SDK initialization](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/android#sdk-initialization) for a full example. Pass `userAttributes` and `clearPreviousAttributes` directly to `initialize`: ```swift TapResearch.initialize(withAPIToken: apiToken, userIdentifier: userIdentifier, userAttributes: ["is_vip": 1], clearPreviousAttributes: false, sdkDelegate: self) { (error: NSError?) in // Handle any error } ``` See [Send user attributes](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/ios#send-user-attributes) for Swift and Objective-C examples. ## User attributes in initialization **Best practice:** If user attributes are known at SDK initialization, pass them through initialization instead of using `sendUserAttributes`. **Benefit:** Faster load times for targeted content. ## Clearing previous attributes Attribute names must be strings and must not begin with `tapresearch_`, which is reserved for TapResearch. Use string or numeric values for targeting. For booleans, send `"true"`/`"false"` or `0`/`1` instead of native booleans. Set `clearPreviousAttributes` to `false` to merge new values with existing attributes, or `true` to replace the attributes you previously sent. --- # User attributes and targeting Source: https://supply-docs.tapresearch.com/docs/3.x/operational-tools/user-attributes User attributes allow you to store additional information about users as key-value pairs. Use them to track information such as: * Game level * Payer status * Custom user segments * Any other data useful to your organization ## SDK setup This page covers how to set up user attributes in the [Publisher Dashboard](https://www.tapresearch.com/supplier_dashboard/overview). **Important:** Attributes only appear in the Publisher Dashboard filters **after they've been sent from the SDK at least once**. For platform-specific implementation details, see: - [Android](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/android#send-user-attributes) - [iOS](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/ios#send-user-attributes) - [Unity](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/unity#send-user-attributes) - [React Native](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/react-native#send-user-attributes) - [Flutter](https://supply-docs.tapresearch.com/docs/3.x/basic-integration/sdk-integration/flutter#sending-user-attributes) Attribute names must be strings and must not begin with `tapresearch_`, which is reserved for TapResearch. Use string or numeric values for targeting. For booleans, send `"true"`/`"false"` or `0`/`1` instead of native booleans. Set `clearPreviousAttributes` to `false` to merge new values with existing attributes, or `true` to replace the attributes you previously sent. ## Targeting based on user attributes You can add up to **3 filters** per piece of content. **Note:** Capping and pacing is only available for currency sale banner content, not Multiple Choice questions. ### Example: Targeting users in France The screenshot shows a partial list of targeting criteria received by TapResearch. Sending different attributes enables you to target different user segments. ### Targeting operators * `is equal to` - Match a specific value, or any value in a list of values * `does not equal` - Exclude a specific value * `is greater/equal to` and `is less/equal to` - Numerical comparisons. For date attributes such as First Seen At, these appear as `is newer than` and `is older than` **Multiple values for one attribute:** Add each value as its own separate entry in the filter — for example, three separate entries for `US`, `CA`, and `GB` when targeting multiple countries, or three separate entries for each tenure level. **Do not** enter them as a single comma-separated string (e.g. `US, CA, GB`) — the filter will treat that as one literal value and it won't match anything. ## Important limitations * **Case sensitivity** - Attributes are case-sensitive: `test` and `Test` are different attributes * **Dates** - Stored as strings: `2020-01-01` and `2020-1-1` are different values * **Booleans** - **Do not use native booleans**. Use stringified values (`"true"`) or integers (`0`, `1`) instead * **Integer vs String** - `1` and `"1"` are different values. For numerical comparisons, send integer values ## Built-in attributes These built-in attributes are also available for targeting: ### Country The user's country location. * Use 2-letter ISO country codes (e.g., `US` for United States) ### First Seen At The first time TapResearch saw this user. * Use ISO8601 date strings: `2020-01-01T00:00:00.000Z` * Use relative dates: `3d` targets users seen more than 3 days ago * Date-only format works: `2020-01-01` equals `2020-01-01T00:00:00.000Z` ### Test Devices Targets only devices in your Test device list. * Use for testing content before going live ### Audience Percentage Targets a percentage of users. * Select groups out of 10 (each group = 10% of users) * Example: Select 3 groups to target 30% of users ## Examples ```kotlin userAttributes = hashMapOf( "testStatus" to "VIP", "testInt" to 2, "testIntString" to "2", "vip_status" to "super-vip", "Some Date" to Instant.now().toString(), // 2023-08-31T10:15:30.00Z // The below will match on relative dates, so you can filter by "a Month Ago" >= 3d "a Month Ago" to LocalDate.now().minus(1, ChronoUnit.MONTHS).toString(), // 2023-07-31 "testCAPSUpper" to "CAPS", // Matches "CAPS" but not "caps" "testCAPSLower" to "caps", // Matches "caps" but not "CAPS" ), ``` ## Technical details ### Attribute caching User attributes are cached for **1 minute** on the backend. * Changes to attributes may take up to **1 minute** to be reflected when querying for content ### Caching examples **Example 1: User Levels Up** Scenario: User sees a placement, levels up, and views the same placement again. ```text playerLevel = 1 changes to playerLevel = 2 ``` You have two pieces of content, one for level 1 and one for level 2. * The user shows content for a placement * The user's level is 1 * The user plays the game and levels up to 2 * The user clicks the placement again and its been less than 1m * The user sees the same content for that placement, not the level 2 content **Example 2: New Attribute Added** Scenario: You have two pieces of content, one for attribute 1 and one for attribute 2. ```text attribute1 = 1 ``` You add an attribute ```text attribute2 = 2 ``` The user has seen a placement, gets an additional attribute they did not have before, and sees new content for that placement * The user shows content for a placement * The user has an additional attribute added to their user attributes that did not exist before * The user clicks the placement again and its been less than 1m * The user sees the _new_ content for that placement, based on the filters for that content **Example 3: Date Targeting** * Relative dates * You want to show content to users who have been playing for 1 month * You'll want to target where `First seen at <= 30d` * Absolute dates * You want to show content to users who have been playing for 1 month * You'll want to target where `First seen at <= 2020-01-01T00:00:00.000Z` **Example 4: Boolean Values** * A user is a VIP * String * Send the attribute `is_vip = "true"` * You'll want to target where `is_vip = "true"` * Integer * Send the attribute `is_vip = 1` * You'll want to target where `is_vip = 1` **Example 5: Multiple Values** * You have multiple user types and want to target some of them * Send the attribute `user_type = "vip"` or `user_type = "normal"` or `user_type = "super-vip"` * Target where `user_type = "vip"` or `user_type = "super-vip"` using the `is equal to` operator — add `vip` and `super-vip` as **two separate entries** in the filter UI, not as one comma-separated value ## Troubleshooting ### Content not matching? **Common issue:** Sending strings instead of integers * Sending `"1"` (string) will not match filters expecting `1` (integer) * **Solution:** Send the value as an integer: `1` ---