Log in

iOS

Integrate SDK into your iOS project. As an example, use ready-made demo apps in Objective-C and Swift.

Basic requirements

Earliest iOS version supported — 12.4 since version SDK 3.1.0 of October 16, 2023.

Integration

Using CocoaPods

Add myTrackerSDK dependency to your Podfile:

pod 'myTrackerSDK'

Run pod install.

Using Swift Package Manager

  1. In your project, select the menu File → Swift Packages → Add Package Dependency... to add a dependency.
  2. Select target you need to add SDK. If your project has one target, it will be selected automatically.
  3. In the Enter package repository URL field, enter the MyTracker SDK repository URL: https://github.com/myTrackerSDK/mytracker-ios-spm. XCode will prompt you to choose an SDK version. The latest version will be used by default.
  4. Click Next. MyTracker SDK will be added as a dependency to your project.
  5. Add the '-ObjC' flag to the Other Linker Flags on the Build Settings tab of your project.

Due to some limitations on the Swift Package Manager side, you should add the AdServices framework to the app target after adding MyTracker SDK.

  1. Select the project file in the XCode navigator and select your app from the Targets list.
  2. Go to the Build Phases tab, add AdServices.framework and AppTrackingTransparency.framework to Link Binary With Libraries. After adding, make sure that you set Status to Optional.

Manually

  1. Download latest version MyTracker iOS SDK and unzip.

  2. Add MyTrackerSDK.framework to project.

  3. Add UIKit, AdSupport, SystemConfiguration, CoreTelephony, CoreData, StoreKit, AdServices, and AppTrackingTransparency frameworks to your project.

  4. Add libz.tbd library to your project.

Initialization

For correct MyTracker SDK operation, set up an instance and initialize inside of the application the didFinishLaunchingWithOptions method of the anAppDelegate class of the app. To initialize SDK, you have to enter SDK_KEY. And before that, you may set different settings for the tracker (configurations, parameters, deep links, etc.).

SDK_KEY is generated automatically after you added your application to MyTracker. To get the key, go to the Application list page, select the required application, and copy the key from the Overview tab.

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    // Setting up the configuration if needed
    MRMyTrackerParams *trackerParams = [MRMyTracker trackerParams];
    // …
    // Setting up params
    // …
    // Initialize the tracker
    [MRMyTracker setupTracker:SDK_KEY];

   return YES;
}

@end
import MyTrackerSDK

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
{

    // Setting up the configuration if needed
    let trackerConfig = MRMyTracker.trackerConfig()
    // ...
    // Setting up params
    // ...
    // Initialize the tracker
    MRMyTracker.setupTracker(SDK_KEY)

    return true
}        

API

Tracker configuration

Configuration can be set up in MRMyTrackerConfig class instance available through the [MRMyTracker trackerConfig] method. Currently available:

trackLaunch: app launch tracking. YES by default.

@property(nonatomic) BOOL trackLaunch;
var trackLaunch: Bool

launchTimeout: an interval (in seconds) during which a new launch is not tracked and a session is not interrupted while app is in background. 30 seconds by default. Possible values range: 30-7200 seconds.

@property(nonatomic) NSTimeInterval launchTimeout;
var launchTimeout: NSTimeInterval

bufferingPeriod: the time during which events are accumulated locally on the device before being sent to the MyTracker server. The default value is 900 seconds, allowed values are: 1-86400 seconds (1 day).

@property(nonatomic) NSTimeInterval bufferingPeriod;
var bufferingPeriod: NSTimeInterval

forcingPeriod: an interval (in seconds) starting from application install/update during which any new event will be send to the server immediately, without local buffering. Default value is set to 0 (immediate sending is disabled), allowed values are 0-432000 seconds (5 days).

@property(nonatomic) NSTimeInterval forcingPeriod;
var forcingPeriod: NSTimeInterval

autotrackPurchase: if payment events should be tracked automatically. YES by default.

@property(nonatomic) BOOL autotrackPurchase;
var autotrackPurchase: Bool

locationTrackingMode: geolocation tracking. Tracking modes:

  • MRLocationTrackingModeNone — location tracking is not available

  • MRLocationTrackingModeCached — system cached value is used

  • MRLocationTrackingModeActive — current location request is used (by default)

No matter what the mode, MyTracker can track user geolocation only if the app already has this permission.

@property(nonatomic) MRLocationTrackingMode locationTrackingMode;
var locationTrackingMode: MRLocationTrackingMode

region, where the data collection server is located.

Since March 1, 2023, the region parameter is disabled. Regardless of the selected value, the data will be sent to servers located in the Russian Federation. To select a different region, please contact our support team

Choose a region based, for example, on current legislation. Available values:

  • MRRegionNotSet — default value

  • MRRegionRu — server on the territory of Russian Federation

  • MRRegionEu — server on the territory of Europe

@property(nonatomic) MRRegion region
var region: MRRegion

registerForSKAdAttribution: SKAdNetwork attribution support. YES by default.

SKAdNetwork is Apple's solution to attribute app installations to a particular campaign while maintaining user privacy.

By default, when a user first launches the app on iOS 14.5+ devices, MyTracker SDK v2.1.2 and newer calls the SKAdNetwork method — registerAppForAdNetworkAttribution, to pass advertisement-driven install notifications to ad networks. For its parts, the ad network can send data to MyTracker. Since iOS 15, you can send a copy of the SKAN data directly to MyTracker in addition to sending it to ad networks.

You can choose to turn the registerForSKAdAttribution parameter off and set up SKAdNetwork methods on your own. Without SKAdNetwork, you will not be able to track attribution on devices if the user denied permission.

For more details, refer to the iOS & SKAdNetwork section and the Apple documentation

@property(nonatomic) BOOL registerForSKAdAttribution;
var registerForSKAdAttribution: Bool

Enable/disable debug mode

Enabling and disabling debug mode can be done via MRMyTracker class static methods. False by default.

+ (void)setDebugMode:(BOOL)enabled;
+ (BOOL)isDebugMode;
static func setDebugMode(_ enabled: Bool)static func isDebugMode() -> Bool

Get SDK logs

You can create your own logger implementation to get MyTracker SDK logs not only in the console, but in your code.

To do this, use the static methods of the MRMyTracker class.

+ (void)setCustomLogger:(nullable id <MRLogger>)customLogger;
+ (nullable id <MRLogger>)customLogger;
static func setCustomLogger(_ customLogger: Logger?)
static func customLogger() -> Logger?

Track users

Set the customUserId parameter to track user stats, not only device. It's a unique user identifier in the project, that you specify at the time of registration. The identifier should remain unchanged even when user switch devices. The parameter allows you to estimate the size and activity of user base, regardless of the number of user devices. Also, you can keep your customer data consistent if a user changes a device. For details, see the User tracking section.

Tracker parameters can be set up in the MRMyTrackerParams class instance available through the [MRMyTracker trackerParams] method. It's essential to set the parameter before tracking events to pass user identifier with every event.

-(void)setUserInfo
{
    MRMyTrackerParams *trackerParams = [MRMyTracker trackerParams];

    // Set user id
    trackerParams.customUserId = @"user_id";

}
func setUserInfo()
{
    let trackerParams = MRMyTracker.trackerParams()

    // Set user id
    trackerParams.customUserId = "user_id"
}

If customUserId was set to the application with an existing registered users, MyTracker cannot calculate exact Lifetime metrics without registration time. For pre-registered users, Lifetime statistic will be count on the date of the first tracked event with customUserId.

To turn off user tracking, pass an empty value in the customUserId parameter.

Track events

Events can be sent via MRMyTracker class static methods. Before you call methods, set the customUserId parameter to pass user identifier with every tracked event.

The following methods for event tracking are available:

Registration event. You should call the method right after user registered in the app. Pass the user identifier in the userId parameter.

userId is a required parameter since SDK version 2.0.6

+ (void)trackRegistrationEvent:(NSString *)userId;
static func trackRegistrationEvent(userId: String) 

Login event. You should call the method right after user successfully authorized in the app. Pass the user identifier in the userId parameter.

userId is a required parameter since SDK version 2.0.6

+ (void)trackLoginEvent:(NSString *)userId;
static func trackLoginEvent(userId: String)

Invite event. Any optional parameters can be passed with event as "key-value" by the optional eventParams parameter. Max key or value length — 255 chars.

+ (void)trackInviteEvent;
+ (void)trackInviteEventWithParams:(NSDictionary<NSString *, NSString *>*)eventParams;
static func trackInviteEvent()
static func trackInviteEvent(eventParams: [String: String]?)

Level up event. The level parameter is optional. Any optional parameters can be passed with event as "key-value" by the optional eventParams parameter. Max key or value length — 255 chars.

+ (void)trackLevelAchieved;
+ (void)trackLevelAchievedWithLevel:(NSNumber *)level;
+ (void)trackLevelAchievedWithLevel:(NSNumber *)level eventParams:(NSDictionary<NSString*, NSString *> *)eventParams;
static func trackLevelAchieved()
static func trackLevelAchieved(level: NSNumber?)
static func trackLevelAchieved(level: NSNumber?, eventParams:[String: String]?)

Any user defined event with a custom name. Any optional parameters can be passed with event as "key-value" by the optional eventParams parameter. Max name, key or value length — 255 chars.

+ (void)trackEventWithName:(NSString *)name;
+ (void)trackEventWithName:(NSString *)name eventParams:(NSDictionary<NSString*, NSString *> *)eventParams;
static func trackEvent(name: NSString)
static func trackEvent(name: NSString, eventParams: [String: String]?)

Example:

NSDictionary *eventCustomParams = @{
    @"someParamKey1" : @"someParamValue1",
    @"someParamKey2" : @"someParamValue2"
  };
[MRMyTracker trackEventWithName:@"eventName" eventParams:eventCustomParams];
let eventCustomParams = ["someParamKey1": "someParamValue1",
                         "someParamKey2": "someParamValue2"]
MRMyTracker.trackEvent(name: "eventName", eventParams:eventCustomParams)

Force sending events from local buffer to server and reset buffering timers.

The SDK, which reduces channel load and lowers impact on app performance, collects all data on the device before sending it off to the server and regularly does so in a compressed format. By default, data is sent every 15 minutes. The interval can be changed to anywhere from 1 second to 1 day through the bufferingPeriod property. If the user has quit the app, the events will be sent during next launch. It's extremely important to analyse certain events as soon as possible, especially in the first sessions since installing the app. The flush() method will help.

+ (void)flush;
static func flush()

To control the result of forced sending, use the flush() method with the Completion parameter. If the events are sent or there are no events to send, the log will show Flush complete, success: 1, if the events failed to be sent for some reason, Flush complete, success: 0.

+ (void)flushWithCompletionBlock:(void (^)(BOOL success))completionBlock;
static func flush(completion: (Bool) -> Void)

Track payments

All in-app payments and subscriptions will be tracked automatically, unless you manually change this behavior by setting the autotrackPurchase property to "NO" (autotrackPurchase = NO). In this case, to track payments, you could use methods below:

+ (void)trackPurchaseWithProduct:(SKProduct *)product transaction:(SKPaymentTransaction *)transaction;
+ (void)trackPurchaseWithProduct:(SKProduct *)product transaction:(SKPaymentTransaction *)transaction eventParams:(NSDictionary<NSString *, NSString *> *)eventParams;
static func trackPurchase(product: SKProduct, transaction: SKPaymentTransaction)
static func trackPurchase(product: SKProduct, transaction: SKPaymentTransaction, eventParams: [String: String]?)

If automatic payments tracking is enabled (autotrackPurchase = YES) these methods calls will be ignored. Required parameters:

Any optional parameters can be passed with event as "key-value" by the optional eventParams parameter. Max key or value length — 255 chars. Returns false, if it’s not added to queue for sending.

S2S tracking

To send data from your server to MyTracker (for example, untracked data, offline events, etc.), you might need a special device identifiers — instanceId. The instanceId is a device identifier (UUID v4), that generated at the first app launch and unchanged until a user delete the app (or app data) from device.

The instanceId can get via the MRMyTracker class static method (you should not use it in the main thread).

+ (NSString *)instanceId;
static let instanceId: String

It's essential to collect instanceId as soon as possible and send the identifier to your server if you use this ID for work with S2S API.

Instead of instanceId you can use any other device ID: idfa, iosVendorId, and/or the user identifier customUserID (in this case, S2S data will generate stats on users). Learn more

Deep links allow sending additional parameters to the app. So a user can go to a specific app screen. There are two types of deep links: regular when parameters to be sent on a launch of the app and deferred when parameters to be sent on a launch of the app after the install. For more details, see the Deep Links section.

To support regular and deferred deep links in your app you need to install a delegate which executes the MRMyTrackerAttributionDelegate protocol. If a deferred deep link is found for the install, the delegate will be called out at the first launch of the app (just once). Also it will be called out at every launch of the app that was triggered by regular deep link.

As a parameter to the didReceiveAttribution method, the MRMyTrackerAttribution attribution object containing the deep link function would be passed.

@interface AppDelegate () <MRMyTrackerAttributionDelegate>
@end


@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    // Setting up the configuration if needed
    MRMyTrackerParams *trackerParams = [MRMyTracker trackerParams];
    // …
    // Setting up params
    // …

    // Install a delegate to receive the deferred deep link
    [MRMyTracker setAttributionDelegate:self];

    // Initialize the tracker
    [MRMyTracker setupTracker:SDK_KEY];

   return YES;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation
{
    return [MRMyTracker handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    return [MRMyTracker handleOpenURL:url options:options];
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray * __nullable restorableObjects))restorationHandler
{
    return [MRMyTracker continueUserActivity:userActivity restorationHandler:restorationHandler];
}

#pragma mark - MRMyTrackerAttributionDelegate

- (void)didReceiveAttribution:(MRMyTrackerAttribution *)attribution
{
    NSString *deeplink = attribution.deeplink;

    // Processing the deep link
    // ...
}

@end
import MyTrackerSDK

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, MRMyTrackerAttributionDelegate
{
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
    {

        // Setting up the configuration if needed
        let trackerConfig = MRMyTracker.trackerConfig()
        // ...
        // Setting up params
        // ...

        // Install a delegate to receive the deferred deep link
        MRMyTracker.setAttributionDelegate(self)

        // Initialize the tracker
        MRMyTracker.setupTracker(SDK_KEY)

        return true
    }

    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool
    {
        return MRMyTracker.handleOpen(url, sourceApplication: sourceApplication, annotation: annotation)
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool
    {
        return MRMyTracker.handleOpen(url, options: options)
    }

    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool
    {
        let handler: ([Any]?) -> Void = {_ in }
        return MRMyTracker.continue(userActivity, restorationHandler: handler)
    }

    // MARK: MRMyTrackerAttributionDelegate

    func didReceive(attribution: MRMyTrackerAttribution)
    {
        let deeplink = attribution.deeplink

        // Processing the deep link
        // ...
    }
}

You may set up a queue NSOperationQueue for method execution when installing the delegate with the setAttributionDelegate:delegateQueue method. If no queue is set up when installing the delegate then the >idReceiveAttribution method would be called out in the main flow.

Was this article helpful?