Резюме #
The Tenjin iOS SDK allows users to track events and installs in their iOS apps. To learn more about Tenjin and our product offering, please visit https://www.tenjin.com.
- Пожалуйста, ознакомьтесь с нашим Примечания к выпуску to see detailed version history.
- For Unity-specific instructions, please visit https://github.com/tenjin/tenjin-unity-sdk.
- For any issues or support, please contact: support@tenjin.com
Notes: #
- Xcode 13 requirement, if you’re using iOS SDK v1.12.17 and higher.
- For AppTrackingTransparency, be sure to update your project
.plistfile and addPrivacy - Tracking Usage Description(NSUserTrackingUsageDescription) along with the text message you want to display to users. This library is only available in iOS 14.0+. - For Apple Search Ads Attribution support, please be sure to upgrade to v1.12.6+ and add the
AdServices.frameworklibrary. This library is only available in iOS 14.3+.
SDK Integration #
Cocoapods #
If you use pods, add pod 'TenjinSDK' к вашему Podfile then run pod install and skip to step 4.
Swift Package Manager #
If you use SPM, add Tenjin’s SDK package through Xcode with this repository [here][43] and skip to step 4.
- Download the latest SDK release [here][21].
- Drag
TenjinSDK.xcframeworkиTenjinSDK.hto your project under build phases -> “Link Binary With Libraries”. - Include the linker flags
-ObjCunder your Build Settings
Steps for Objective-C projects #
- Go to your AppDelegate file, by default
AppDelegate.m, и#import "TenjinSDK.h". - Получите свой
SDK_KEYсо страницы вашего приложения. Примечание:SDK_KEYуникален для каждого вашего приложения. Вы можете создать до 3 ключей для одного приложения.

- В вашем
didFinishLaunchingWithOptionsmethod add:
[TenjinSDK initialize:@" "];
[TenjinSDK connect];- To enable Tenjin iOS SDK debug logs add:
[TenjinSDK debugLogs];Here’s an example of what your integration in Objective-C projects should look like in your AppDelegate.m file:
#import "TenjinSDK.h"
@implementation TJNAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[TenjinSDK initialize:@" "];
[TenjinSDK connect];
//All your other stuff
...
}
Steps for Swift projects #
- Add Objective-C Bridging Header file for swift projects,
- Create a header file
- File -> New -> File -> “Sources”
- Choose “Header” File – > Click Next
- The header file name should “YourProjectName-Bridging-Header” – Under “Targets” -> Select the app target -> Click Next
- In the header file – “YourProjectName-Bridging-Header.h”
- Add the following,
- Create a header file
#import "TenjinSDK.h"-
- Go to the app target and under “Build Settings”
- Go to the section “Swift Compiler – General”
- Go to the sub-section “Objective-C Bridging Header” and drag the header file – “YourProjectName-Bridging-Header.h” to the field.
- Go to the app target and under “Build Settings”
- Получите свой
SDK_KEYсо страницы вашего приложения. Примечание:SDK_KEYуникален для каждого вашего приложения. Вы можете создать до 3 ключей для одного приложения.

- a. In your
didFinishLaunchingWithOptionsmethod add:
TenjinSDK.getInstance(" ")
TenjinSDK.connect()If you are using Swift 5, use the getInstance() method instead of init(). See our sample Swift app
- To enable Tenjin iOS SDK debug logs add:
TenjinSDK.debugLogs();Here’s an example of what your integration in Swift projects should look like in your AppDelegate.swift file:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
TenjinSDK.getInstance(" ")
TenjinSDK.connect()
return true
}
ПРИМЕЧАНИЕ: Пожалуйста, убедитесь, что вы внедрили этот код в каждый didFinishLaunchingWithOptions, Не только при первом открытии приложения.
Alternate initialization to handle deep links from other services. If you use other services to produce deferred deep links, you can pass Tenjin those deep links to handle the attribution logic with your Tenjin enabled deep links.
#import "TenjinSDK.h"
@implementation TJNAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[TenjinSDK init:@" "];
//get your deep link from your other 3rd party service
NSURL *url = [NSURL withString: @"your_deep_link"];
//if you have a deep link that's generated from a third party service then pass it to tenjin to handle the attribution of deep links holistically
if(url) {
[TenjinSDK connectWithDeferredDeeplink:url];
}
else{
[TenjinSDK connect];
}
//All your other stuff
//...
}
Проверить, работает ли интеграция, можно через наш Инструмент для получения данных об устройстве в режиме реального времени. Добавьте свой рекламный идентификатор или IDFA/GAID в список тестовых устройств. Это можно найти в разделе Поддержка -\> Тестовые устройства. Go to the Страница SDK Live and send the test events from your app. You should see live events come in:
Tenjin initialization with ATTrackingManager #
Starting with iOS 14, you have the option to show the initial ATTrackingManager permissions prompt and selection to opt in/opt out users.
If the device doesn’t accept tracking permission, IDFA will become zero. If the device accepts tracking permission, the connect() method will send the IDFA to our servers.
You can also still call Tenjin connect(), without using ATTrackingManager. You can choose not to implement ATT if you don’t intend to access or pass the IDFA for any users to Tenjin.
#import "TenjinSDK.h"
@implementation TJNAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[TenjinSDK init:@" "];
if (@available(iOS 14, *)) {
[ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
[TenjinSDK connect];
}];
} else {
[TenjinSDK connect];
}
}
Displaying an ATT permission prompt #
To comply with Apple’s ATT guidelines, you must provide a description for the ATT permission prompt, then implement the permission request in your application.
> Note: You must implement the permission request before serving ads in your game.
Configuring a user tracking description #
Apple requires a description for the ATT permission prompt. You need to set the description with the NSUserTrackingUsageDescription key in the Info.plist file of your Xcode project. You have to provide a message that informs the user why you are requesting permission to use device tracking data:
- In your Xcode project navigator, open the
Info.plistfile. - Click the add button (+) beside any key in the property list editor to create a new property key.
- Enter the key name
NSUserTrackingUsageDescription. - Select a string value type.
- Enter the app tracking transparency message in the value field. Some examples include:
- “We will use your data to provide a better and personalized ad experience.”
- “We try to show ads for apps and products that will be most interesting to you based on the apps you use, the device you are on, and the country you are in.”
- “We try to show ads for apps and products that will be most interesting to you based on the apps you use.”
> Note: Apple provides specific [app store guidelines][24] that define acceptable use and messaging for all end-user facing privacy-related features. Tenjin does not provide legal advice. Therefore, the information on this page is not a substitute for seeking your own legal counsel to determine the legal requirements of your business and processes, and how to address them.
SKAdNetwork and Conversion value #
As part of SKAdNetwork, we created wrapper method for updatePostbackConversionValue(_:). Our method will register the equivalent SKAdNetwork methods and also send the conversion values to our servers.
updatePostbackConversionValue(\_:) you will provide an integer between 0 and 63 (decimal value, not binary). This value should directly reflect an in-app event or user milestone based on the specific conversion value strategy you establish for your app. We strongly recommend consulting [this][25] page o plan your conversion value implementation before coding this logic.
As of iOS 16.1, which supports SKAdNetwork 4.0, you can now send coarseValue (String, with possible variants being “low”, “medium” or “high”) and lockWindow (Boolean) as parameters on the update postback method:
updatePostbackConversionValue(_ conversionValue: Integer, coarseValue: String)
updatePostbackConversionValue(_ conversionValue: Integer, coarseValue: String, lockWindow: Bool)
- For iOS version 16.1+ which supports SKAdNetwork 4.0, you can call this method as many times as you want and can make the conversion value lower or higher than the previous value.
- For iOS versions lower than 16.1 supporting SKAdnetWork versions lower than 4.0, you can call this method and our SDK will automatically detect the iOS version and update
conversionValueonly.
#import "TenjinSDK.h"
@implementation TJNAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[TenjinSDK initialize:@" "];
[TenjinSDK connect];
//
// This will call [SKAdNetwork updatePostbackConversionValue: ]
// and also send conversion value to our servers.
//
// You will need to use a value between 0-63.
//
[TenjinSDK updatePostbackConversionValue: <Integer between 0 и 63>];
// For iOS 16.1+ (SKAN 4.0)
[TenjinSDK updatePostbackConversionValue: <Integer between 0 и 63> coarseValue:@"medium"];
[TenjinSDK updatePostbackConversionValue: <Integer between 0 и 63> coarseValue:@"medium" lockWindow:true];
}
}
SKAdNetwork and iOS 15+ Advertiser Postbacks #
To specify Tenjin as the destination for your [SK Ad Network postbacks][26], do the following:
- Select
Info.plistin the Project navigator in Xcode. - Click the Add button (+) beside a key in the property list editor and press Return.
- Type the key name
NSAdvertisingAttributionReportEndpoint. - Choose String from the pop-up menu in the Type column.
- Enter
https://tenjin-skan.com
These steps are an adaption from Apple’s instructions at [https://developer.apple.com/documentation/storekit/skadnetwork/configuring\_an\_advertised\_app][27].
GDPR #
В соответствии с требованиями GDPR, с помощью SDK Tenjin вы можете отказаться от использования устройств/пользователей или выбрать, какие именно параметры, связанные с устройством, следует включить или исключить. OptOut() не будет отправлять никаких API-запросов в Tenjin, и мы не будем обрабатывать никаких событий.
Чтобы отказаться от участия/отказаться от участия:
#import "TenjinSDK.h"
@implementation TJNAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[TenjinSDK initialize:@" "];
if ([self checkOptInValue]) {
[TenjinSDK optIn];
}
else {
[TenjinSDK optOut];
}
[TenjinSDK connect];
//All your other stuff
//..
}
-(BOOL) checkOptInValue
{
// check opt-in value
// return YES; // if user opted-in
return NO;
}
To opt-in/opt-out specific device-related parameters, you can use the OptInParams() или OptOutParams(). OptInParams() будет отправлять только те параметры устройства, которые указаны. OptOutParams() отправит все параметры, связанные с устройством, кроме тех, которые указаны.
- Обратите внимание, что для правильного отслеживания устройств в системе Tenjin нам необходим следующий параметр. Если обязательный параметр отсутствует, событие не будет обработано или записано.
developer_device_id
If you intend to use Google Ads, you will also need to add: рекламный идентификатор, developer_device_id, платформа, os_version,версия приложения, локаль, модель устройства, и build_id.
Если вы хотите получить только определенные параметры, связанные с устройством, используйте OptInParams(). В примере ниже мы рассмотрим только эти параметры, связанные с устройством: ip_адрес, рекламный идентификатор, developer_device_id, limit_ad_tracking, и iad:
[TenjinSDK initialize:@" "];
NSArray *optInParams = @[@"ip_адрес", @"рекламный идентификатор", @"developer_device_id", @"limit_ad_tracking", @"iad"];
[TenjinSDK optInParams:optInParams];
[TenjinSDK connect];
Если вы хотите отправить ВСЕ параметры, кроме определенных параметров, связанных с устройством, используйте OptOutParams(). В приведенном ниже примере мы отправим ВСЕ параметры, связанные с устройством, кроме: локаль, timezone, и build_id параметры.
[TenjinSDK initialize:@" "];
NSArray *optOutParams = @[@"country", @"timezone", @"language"];
[TenjinSDK optOutParams:optOutParams];
[TenjinSDK connect];
Включение/выключение с помощью CMP #
Вы можете автоматически отказаться от участия или отказаться от участия, используя свои согласия CMP (цель 1), которые уже сохранены в устройстве пользователя. Метод возвращает булево значение, чтобы сообщить вам о том, был ли пользователь согласен или нет.
optInOutUsingCMP()
[TenjinSDK initialize:@" "];
optInOut = [TenjinSDK optInOutUsingCMP];
Параметры, связанные с устройством #
| Param | Description | Reference |
|---|---|---|
| ip\_address | IP Address | |
| advertising\_id | Device Advertising ID | [iOS][28] |
| developer\_device\_id | ID for Vendor | [iOS][29] |
| limit\_ad\_tracking | limit ad tracking enabled | [iOS][30] |
| платформа | платформа | iOS |
| iad | Apple Search Ad parameters | [iOS][31] |
| os\_version | operating system version | [iOS][32] |
| device | device name | [iOS (hw.machine)][33] |
| device\_model | device model | [iOS (hw.model)][34] |
| device\_model\_name | device machine | [iOS (hw.model)][35] |
| device\_cpu | device cpu name | [iOS (hw.cputype)][36] |
| os\_version\_release | operating system version | [iOS][37] |
| build\_id | build ID | [iOS (kern.osversion)][38] |
| локаль | device locale | [iOS][39] |
| country | locale country | [iOS][40] |
| timezone | timezone | [iOS][41] |
События покупки #
Pass (SKPaymentTransaction *) transaction и (NSData *)receipt object, after the verification of the purchase, and then you can pass SKPaymentTransactionStatePurchased to Tenjin for the transaction which was purchased:
//Get the NSData receipt
NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
//Pass the transaction and the receiptData to Tenjin
[TenjinSDK транзакция: транзакция andReceipt: receiptData];
Отказ от ответственности: Если вы впервые внедряете события покупки в Tenjin, обязательно проверьте данные с помощью других инструментов, которые вы используете, прежде чем начинать масштабировать кампании по привлечению пользователей с использованием данных о покупках.
(Flexible App Store Commission setup) Choose between 15% and 30% App Store’s revenue commission via our new setup. The steps are –
- Перейдите в раздел КОНФИГУРИРОВАНИЕ -> Приложения
- Нажмите на приложение, для которого вы хотите его изменить
- В разделе ‘Комиссия App Store’ нажмите ‘Изменить’.’
- Выберите 30% или 15% в качестве желаемой комиссии магазина приложений.
- Выберите дату начала и дату окончания (или вы можете оставить дату окончания пустой, если вам не нужна дата окончания).
- Нажмите кнопку Сохранить (примечание: комиссия 15% может применяться только к датам, перенесенным вперед, а не к историческим датам. Поэтому установите дату начала с даты внесения изменений и вперед)
Subscription IAP #
ВАЖНО: If you have subscription IAP, you will need to add your app’s public key in the Приборная панель Тендзина. You can retrieve your iOS App-Specific Shared Secret from the iTunes Connect Console \> Select your app \> App Information \> App-Specific Shared Secret.
Kindly note that you are responsible to send a subscription transaction one time during each subscription interval (i.e., For example, for a monthly subscription, you will need to send us 1 transaction per month).
In the example timeline below, a transaction event should only be sent at the “First Charge” and “Renewal” events. During the trial period, do not send Tenjin the transaction event.
For more information on subscriptions, please see: Apple documentation on Working with Subscriptions
Нестандартные события #
IMPORTANT: DO NOT SEND CUSTOM EVENTS BEFORE THE CONNECT/INITIALIZATION event (above). The initialization must come before sending any custom events.
ВАЖНО: Ограничьте названия пользовательских событий до 80 символов. Не превышайте 500 уникальных названий пользовательских событий.
You can also use the Tenjin SDK to pass a custom event:
sendEventWithName: (NSString *)eventNameи
You can use these to pass Tenjin custom interactions with your app to tie this to user level cost from each acquisition source that you use through Tenjin’s platform. Here are some examples of usage:
//send a particular event for when someone swipes on a part of your app
[TenjinSDK sendEventWithName:@"swipe_right"];Custom events can also pass an NSInteger eventValue. Tenjin will use this eventValue as a count or sum for all custom events with the same eventName. The eventValue MUST BE AN INTEGER. If the eventValue is not an integer, we will not send the event.
//send a particular event for when someone swipes and an event value on a part of your app
[TenjinSDK sendEventWithName:@"swipe_right" andEventValue:@"1"];Интеграция между серверами #
Тендзин предлагает межсерверная интеграция. Это позволит вам отправлять события установки и после установки непосредственно с ваших серверов на серверы Tenjin без необходимости интеграции SDK. Если вы хотите получить доступ к документации, пожалуйста, отправьте письмо на support@tenjin.com.
Параметр App Subversion для A/B-тестирования (требуется DataVault) #
Если вы проводите A/B-тесты и хотите получить отчет о различиях, мы можем добавить числовое значение к версии вашего приложения, используя appendAppSubversion method. For example, if your app version 1.0.1, и установите appendAppSubversion: @8888, it will report as 1.0.1.8888.
Эти данные появятся в DataVault, где вы сможете запускать отчеты, используя значения субверсии приложения.
[TenjinSDK initialize:@" "];
[TenjinSDK appendAppSubversion:@8888];
[TenjinSDK connect];Интеграция доходов от рекламы на уровне впечатлений #
Tenjin поддерживает возможность интеграции с функцией Impression Level Ad Revenue (ILRD) из,
- AppLovin
- Unity LevelPlay
- ГиперБид
- AdMob
- TopOn
- CAS
- TradPlus
This feature allows you to receive events which correspond to your ad revenue that is affected by each advertisement show to a user. To enable this feature, follow the below instructions.
ILRD is a paid feature, so please contact your Tenjin account manager to discuss the price at first before sending ILRD events.
Кампании LiveOps #
Tenjin supports retrieving of user attribution information, like sourcing ad network and campaign, from the SDK. This will allow developers to collect and analyze user-level attribution data in real-time. Here are the possible use cases using Tenjin LiveOps Campaigns:
- Если у вас есть собственный инструмент анлитики данных, пользовательский обратный вызов позволит вам привязать данные атрибуции к вашим внутриигровым данным на уровне устройств.
- Show different app content depending on where the user comes from. For example, if user A is attributed to organic and user B is attributed to Facebook and user B is likely to be more engaged with your app, then you want to show a special in-game offer after the user installs the app. If you want to discuss more specific use cases, please write to support@tenjin.com. LiveOps Campaigns is a paid feature, so please contact your Tenjin account manager if you are interested in.
Идентификатор пользователя клиента #
Вы можете задавать и получать идентификатор пользователя клиента, чтобы отправлять его в качестве параметра в событиях.
setCustomerUserId(userId: "user_id") getCustomerUserId()
[TenjinSDK initialize:@" "];
[TenjinSDK setCustomerUserId:@"user_id"];
userId = [TenjinSDK getCustomerUserId];
Идентификатор установки аналитики #
Вы можете получить идентификатор аналитика, который генерируется случайным образом и сохраняется в локальном хранилище устройства. getAnalyticsInstallationId()
[TenjinSDK initialize:@" "];
analyticsId = [TenjinSDK getAnalyticsInstallationId]; Retry/cache events #
Вы можете включить/выключить повторную попытку и кэширование всех событий при неудачных запросах или отсутствии интернет-соединения у пользователей. Эти события будут отправляться после того, как новое событие будет добавлено в очередь и пользователь восстановит соединение.
setCacheEventSetting(true)
[TenjinSDK setCacheEventSetting:true];Параметры Google DMA #
Если у вас уже есть встроенный CMP, параметры Google DMA будут автоматически собраны Tenjin SDK. В Tenjin SDK ничего не нужно реализовывать, если у вас есть встроенный CMP.. Если вы хотите переопределить CMP или просто хотите создать собственные механизмы согласия, вы можете использовать следующее:
setGoogleDMAParametersWithAdPersonalization(bool, bool)
[[TeninSDK sharedInstance] setGoogleDMAParametersWithAdPersonalization:adPersonalization adUserData:adUserData]; To explicitly manage the collection of Google DMA parameters, you have the flexibility to opt in or opt out at any time. While the default setting is to opt in, you can easily adjust your preferences using the optInGoogleDMA or optOutGoogleDMA methods, ensuring full control over your data privacy settings:
[TeninSDK optInGoogleDMA];
[TeninSDK optOutGoogleDMA]; [1]: #sdk-integration [2]: #tenjin-initialization-with-attrackingmanager [3]: #displaying-an-att-permission-prompt [4]: #configuring-a-user-tracking-description [5]: #skadnetwork-and-conversion-value [6]: #skadnetwork-and-ios-15-advertiser-postbacks [7]: #tenjin-and-gdpr [8]: #devicerelated-parameters [9]: #purchase-events [10]: #subscription-iap [11]: #custom-events [12]: #deferred-deeplink [13]: #servertoserver-integration [14]: #app-subversion-parameter-for-ab-testing-requires-datavault [15]: #impression-level-ad-revenue-integration [16]: #liveops-campaigns [17]: https://github.com/tenjin/tenjin-ios-sdk/releases [18]: https://tenjin.io/dashboard/organizations [19]: https://github.com/tenjin/tenjin-ios-sdk-swift-demo [20]: https://developer.apple.com/app-store/user-privacy-and-data-use/ [21]: https://github.com/tenjin/tenjin-ios-sdk/releases [22]: https://tenjin.io/dashboard/organizations [23]: https://github.com/tenjin/tenjin-ios-sdk-swift [24]: https://developer.apple.com/app-store/user-privacy-and-data-use/ [25]: https://docs.tenjin.com/docs/conversion-value-mapping-recommendations [26]: https://developer.apple.com/documentation/storekit/skadnetwork/receiving_ad_attributions_and_postbacks [27]: https://developer.apple.com/documentation/storekit/skadnetwork/configuring_an_advertised_app [28]: https://developer.apple.com/documentation/adsupport/asidentifiermanager/1614151-advertisingidentifier [29]: https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor [30]: https://developer.apple.com/documentation/adsupport/asidentifiermanager/1614148-isadvertisingtrackingenabled [31]: https://searchads.apple.com/advanced/help/measure-results/#attribution-api [32]: https://developer.apple.com/documentation/uikit/uidevice/1620043-systemversion [33]: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/sysctl.3.html [34]: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/sysctl.3.html [35]: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/sysctl.3.html [36]: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/sysctl.3.html [37]: https://developer.apple.com/documentation/uikit/uidevice/1620043-systemversion [38]: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/sysctl.3.html [39]: https://developer.apple.com/documentation/foundation/nslocalekey [40]: https://developer.apple.com/documentation/foundation/nslocalecountrycode [41]: https://developer.apple.com/documentation/foundation/nstimezone/1387209-localtimezone [42]: #liveops-campaigns [43]: #analytics-installation-id [45]: #retry-cache [46]: #customer-user-id [47]: #opt-inout-using-cmp [48]: #google-dma-parameters [image-1]: https://github.com/tenjin/tenjin-ios-sdk/blob/master/assets/ios_link_binary.png?raw=true “dashboard” [image-2]: https://github.com/tenjin/tenjin-ios-sdk/raw/master/assets/ios_linker_flags.png?raw=true “dashboard” [image-3]: https://s3.amazonaws.com/tenjin-instructions/sdk_live_open_events.png
