Usage examples

Initializing the library with the extended configuration

To initialize the library with the extended startup configuration:

  1. Initialize the YMMYandexMetricaConfiguration instance.
  2. Specify the configuration settings using methods of the YMMYandexMetricaConfiguration class. For example, enable logging or set a session timeout.
  3. Pass the YMMYandexMetricaConfiguration instance into the method +activateWithConfiguration: of the YMMYandexMetrica class.

The parameters of the extended configuration are applied from the time of library initialization. To configure the library while the application is running, use the methods of the YMMYandexMetrica class.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Creating an extended library configuration.
    YMMYandexMetricaConfiguration *configuration = [[YMMYandexMetricaConfiguration alloc] initWithApiKey:@"API_key"];
    // Setting up the configuration. For example, to enable logging.
    configuration.logs = YES;
    ...
    // Initializing the AppMetrica SDK.
    [YMMYandexMetrica activateWithConfiguration:configuration];
}
Copied to clipboard

Sending statistics to an additional API key

Sending data to an additional API key allows you to collect own statistics for these API keys. You can use this to control access to information for other users. For example, to provide access to statistics for analysts you can duplicate sending marketing data for the additional API key. Thus they will only have access to the information they need.

To send data to an additional API key, you must use reporters. Just like for the main API key, you can set up an extended startup configuration for a reporter, send events, profile information, and data about in-app purchases. The reporter can work without the AppMetrica SDK initialization.

Step 1. (Optional) Initialize a reporter with an extended configuration

Attention. The reporter with the extended configuration should be initialized before the first call to the reporter. Otherwise, the reporter will be initialized without a configuration.

To initialize a reporter with an extended configuration:

  1. Initialize the YMMReporterConfiguration instance.
  2. Specify the configuration settings using methods of the YMMReporterConfiguration class. For example, enable logging or set a session timeout.
  3. Pass the YMMReporterConfiguration instance into the method +activateReporterWithConfiguration: of the YMMYandexMetrica class.

This configuration is used for a reporter with the specified API key. You can set up your own configuration for each additional API key.

// Creating an extended library configuration.
// To create it, pass an API_key that is different from the app's API_key.
YMMReporterConfiguration *reporterConfiguration = [[YMMReporterConfiguration alloc] initWithApiKey:@"API_key"];
// Setting up the configuration. For example, to enable logging.
reporterConfiguration.logs = YES;
...
// Initializing a reporter.
[YMMYandexMetrica activateReporterWithConfiguration:[reporterConfiguration copy]];
Copied to clipboard

Step 2. Configure sending data using a reporter

To send statistics data to another API key:

  1. Use the -reporterForApiKey: method of the YMMYandexMetrica class to get the object that implements the YMMYandexMetricaReporting protocol.

    If the reporter was not initialized with the extended configuration, calling this method will initialize the reporter for the specified API key.

  2. Use methods of the YMMYandexMetricaReporting protocol to send errors, events, and revenue.
  3. To ensure that sessions are tracked correctly, set up sending session start and pause events for each reporter.
id<YMMYandexMetricaReporting> reporter = [YMMYandexMetrica reporterForApiKey:@"API_key"];
[reporter resumeSession];
...
[reporter reportEvent:@"Updates installed" onFailure:^(NSError *error) {
    NSLog(@"REPORT ERROR: %@", [error localizedDescription]);
}];
...
[reporter pauseSession];
Copied to clipboard

Monitoring app crashes

Reports on app crashes are sent by default.

To disable automatic monitoring, initialize the library with the configuration in which sending crashes is disabled. To do this, set the NO value for the crashReporting property of the extended library configuration YMMYandexMetricaConfiguration.

// Creating an extended library configuration.
YMMYandexMetricaConfiguration *configuration = [[YMMYandexMetricaConfiguration alloc] initWithApiKey:@"API_key"];
// Disabling sending the information on crashes of the application.
configuration.crashReporting = NO;
// Initializing the AppMetrica SDK.
[YMMYandexMetrica activateWithConfiguration:configuration];
Copied to clipboard

Determining the location

Location accuracy depends on the configuration that the library uses for initialization:
With the locationTracking option enabled

The location is determined with accuracy to the city. You can retrieve this information in reports and via the Logs API.

The app requests GPS access. Battery consumption may increase.

With the locationTracking option disabled
The location is determined by the IP address with accuracy to the country. You can retrieve this information in reports, but not via the Logs API.

The app requests GPS access. Battery consumption does not increase.

Note. If you have enabled IP address masking, AppMetrica determines location with the accuracy to the country by the unmasked part of the IP address.

By default, the AppMetrica SDK is initialized with the enabled locationTracking option. AppMetrica SDK does not request the permission for getting location data. You should implement this using the methods of the CLLocationManager class.

To initialize a library with the disabled locationTracking option, set the NO value for the locationTracking property of the YMMYandexMetricaConfiguration configuration.

// Creating an extended library configuration.
YMMYandexMetricaConfiguration *configuration = [[YMMYandexMetricaConfiguration alloc] initWithApiKey:API_key];
// Disabling sending information about the device location.
configuration.locationTracking = NO;
// Initializing the AppMetrica SDK.
[YMMYandexMetrica activateWithConfiguration:configuration];
Copied to clipboard

To disable locationTracking after initializing the library, use the method +setLocationTracking: of the YMMYandexMetrica class:

[YMMYandexMetrica setTrackLocationEnabled:NO];
Copied to clipboard

Setting device location manually

Before sending custom information on the location of the device, make sure that the reporting is not disabled.

By default, the device location is detected by the library.

To send custom device location information, pass the CLLocation instance into the method +setLocation: of the YMMYandexMetrica class.

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    [YMMYandexMetrica setLocation:newLocation];
}
Copied to clipboard

To send your own device location information using the startup configuration, pass the CLLocation instance to the location property when creating the extended library configuration YMMYandexMetricaConfiguration.

Sending a custom event

To send a custom event without nested parameters, pass in the method +reportEvent:onFailure: of the YMMYandexMetrica class the following parameter:
  • message — Short name or description of the event;
  • onFailure — The block the error is passed to. If you do not want to track the error, pass nil for this block.
[YMMYandexMetrica reportEvent:@"Updates installed" onFailure:^(NSError *error) {
    NSLog(@"DID FAIL REPORT EVENT: %@", message);
    NSLog(@"REPORT ERROR: %@", [error localizedDescription]);
}];
Copied to clipboard

Sending a custom event with nested parameters

To send a custom event with nested parameters, pass into the method +reportEvent:params:onFailure: of the YMMYandexMetrica class the following parameter:
  • message — Short name or description of the event;
  • params — Nested parameters as “key-value” pairs;

    The AppMetrica web interface displays up to five nesting levels for events. So if an event has six or more levels, only the top five are shown in the report. You can use the Reporting API to get up to ten levels.

  • onFailure — The block the error is passed to. If you do not want to track the error, pass nil for this block.
NSDictionary *params = @{@"key1": @"value1", @"key2": @"value2"};
[YMMYandexMetrica reportEvent:@"EVENT"
                   parameters:params
                    onFailure:^(NSError *error) {
                        NSLog(@"error: %@", [error localizedDescription]);
                    }];
Copied to clipboard

For more information about events, see Events.

Sending an error message

To send custom error message, pass in the method +reportError:exception:onFailure: of the YMMYandexMetrica class the following parameters:

  • message — Short name or description of the event;
  • exceptionNSException type object to pass to the server. It can take the nil value.
  • onFailure — The block the error is passed to. If you do not want to track the error, pass nil for this block.
@try {
    [self doWork];
}
@catch (NSException *exception) {
    [YMMYandexMetrica reportError:@"doWork failed"
                        exception:exception
                        onFailure:nil];
}
Copied to clipboard

Sending profile attributes

To send profile attributes, pass in the method +reportUserProfile:onFailure: of the YMMYandexMetrica class the following parameters:

  • userProfile — The YMMUserProfile instance that contains an array of attribute updates. To create profile attributes, use methods of the YMMProfileAttribute class.
  • onFailure — The block the error is passed to. If you do not want to track the error, pass nil for this block.
YMMMutableUserProfile *profile = [[YMMMutableUserProfile alloc] init];
// Updating a single user profile attribute.
id<YMMCustomCounterAttribute> timeLeftAttribute = [YMMProfileAttribute customCounter:@"time_left"];
[profile apply:[timeLeftAttribute withDelta:-4.42]];
// Updating multiple attributes.
[profile applyFromArray:@[
    // Updating predefined attributes.
    [[YMMProfileAttribute name] withValue:@"John"],
    [[YMMProfileAttribute gender] withValue:YMMGenderTypeMale],
    [[YMMProfileAttribute birthDate] withAge:24],
    [[YMMProfileAttribute notificationsEnabled] withValue:NO],
    // Updating custom attributes.
    [[YMMProfileAttribute customString:@"born_in"] withValueIfUndefined:@"Moscow"],
    [[YMMProfileAttribute customString:@"address"] withValueReset],
    [[YMMProfileAttribute customNumber:@"age"] withValue:24],
    [[YMMProfileAttribute customCounter:@"logins_count"] withDelta:1],
    [[YMMProfileAttribute customBool:@"has_premium"] withValue:YES]
]];
// ProfieID is set using the method of the YMMYandexMetrica class.
[YMMYandexMetrica setUserProfileID:@"id"];

// Sending profile attributes.
[YMMYandexMetrica reportUserProfile:[profile copy] onFailure:^(NSError *error) {
    NSLog(@"Error: %@", error);
}];
Copied to clipboard

Sending ProfileId

To send ProfileId, use the method +setUserProfileID: of the YMMYandexMetrica class.

If you don't configure ProfileId sending in the SDK, the web interface displays the appmetrica_device_id value.

[YMMYandexMetrica setUserProfileID:@"id"];
Copied to clipboard

Sending Revenue

AppMetrica supports the revenue validation for purchases made using the StoreKit library. Validation lets you filter purchases made from hacked apps. If validation is enabled and a purchase fails, it isn't shown in reports.

Note. To validate purchases, enable the validation in the settings. For more information, see Sending information about a purchase on iOS.

Step 1. Test sending Revenue

AppMetrica doesn't let you segment Revenue into “test” and “not test”. If you use the main API key for debugging purchases, the test purchases are included in general statistics. Therefore, to debug Revenue sending, use a reporter to send statistics to the additional API key.

This section outlines the steps for sending Revenue to the additional API key:

To validate purchases on iOS, configure sending the transactionID and receiptData fields in the implementation of the completion of the transaction:

  1. Initialize the YMMMutableRevenueInfo instance.
  2. To validate a purchase, specify transactionID and receiptData. You should receive them before invoking [[SKPaymentQueue defaultQueue] finishTransaction:transaction].
  3. Send the YMMMutableRevenueInfo instance to the test API key using the YMMYandexMetricaReporting reporter. For more information on reporters, see Sending statistics to an additional API key.
- (void)completeTransaction:(SKPaymentTransaction *)transaction
{
    ...
    NSDecimalNumber *price = [NSDecimalNumber decimalNumberWithString:@"2100.5"];
    // Initializing the Revenue instance.
    YMMMutableRevenueInfo *revenueInfo = [[YMMMutableRevenueInfo alloc] initWithPriceDecimal:price currency:@"BYN"];
    revenueInfo.productID = @"TV soundbar";
    revenueInfo.quantity = 2;
    revenueInfo.payload = @{ @"source": @"AppStore" };
    // Set purchase information for validation.
    revenueInfo.transactionID = transaction.transactionIdentifier;
    revenueInfo.receiptData = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]];
    // Sending the Revenue instance using reporter.
    id<YMMYandexMetricaReporting> reporter = [YMMYandexMetrica reporterForApiKey:@"Testing API key"];
    [reporter reportRevenue:[revenueInfo copy] onFailure:^(NSError *error) {
        NSLog(@"Revenue error: %@", error);
    }];
    // Remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
Copied to clipboard

Step 2. Configure sending Revenue to the main API key

After successful testing, configure sending Revenue to the main API key.

To send the YMMMutableRevenueInfo instance to the main API key, use the +reportRevenue:onFailure: method of the YMMYandexMetrica class.

...
// Sending the Revenue instance.
[YMMYandexMetrica reportRevenue:[revenueInfo copy] onFailure:^(NSError *error) {
    NSLog(@"Revenue error: %@", error);
}];
Copied to clipboard

Setting the length of the session timeout

To change the length of the timeout, pass the value in seconds to the sessionTimeout property of the library configuration YMMYandexMetricaConfiguration.

By default, the session timeout is 10 seconds. The minimum acceptable value for the sessionTimeout property is 10 seconds.

// Creating an extended library configuration.
YMMYandexMetricaConfiguration *configuration = [[YMMYandexMetricaConfiguration alloc] initWithApiKey:@"API_key"];
// Setting the session timeout.
configuration.sessionTimeout = 15;
// Initializing the AppMetrica SDK.
[YMMYandexMetrica activateWithConfiguration:configuration];
Copied to clipboard

Setting the app version

By default, the app version is set in the app configuration file Info.plist (CFBundleShortVersionString).

To specify the app version from the code, pass the app version to the appVersion property of the library configuration YMMYandexMetricaConfiguration.

// Creating an extended library configuration.
YMMYandexMetricaConfiguration *configuration = [[YMMYandexMetricaConfiguration alloc] initWithApiKey:@"API_key"];
// Setting the app version.
configuration.appVersion = @"1.13.2";
// Initializing the AppMetrica SDK.
[YMMYandexMetrica activateWithConfiguration:configuration];
Copied to clipboard

Tracking app openings via deeplinks

Tracking app opening is necessary for correct tracking of the remarketing campaigns.

To track app openings via deeplinks and Universal Links, use the +handleOpenURL: method of the YMMYandexMetrica class.

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

// Delegate for tracking Universal links.
- (BOOL)application:(UIApplication *)application
    continueUserActivity:(NSUserActivity *)userActivity
    restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler
{
    if ([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]) {
        [YMMYandexMetrica handleOpenURL:userActivity.webpageURL];
    }
    return YES;
}
Copied to clipboard

Tracking new users

By default, the user is counted as a new user when the app is opened for the first time. If you connect the AppMetrica SDK to an application that already has active users, you can set up tracking new users. To configure this, initialize the AppMetrica SDK using the extended configuration YMMYandexMetricaConfiguration.

BOOL isFirstLaunch = NO;
// Creating an extended library configuration.
YMMYandexMetricaConfiguration *configuration = [[YMMYandexMetricaConfiguration alloc] initWithApiKey:@"API_key"];
// Implement the logic for detecting whether the app is starting for the first time.
// For example, you can check for files (settings, databases, and so on),
// which the app creates on its first launch.
if (conditions) {
    isFirstLaunch = YES;
}
configuration.handleFirstActivationAsUpdateEnabled = !isFirstLaunch;
// Initializing the AppMetrica SDK.
[YMMYandexMetrica activateWithConfiguration:configuration];
Copied to clipboard

Disable and enable sending statistics

If you need confirmation from the user before sending statistical data, you should initialize the library with the disabled sending option. To do this, set the NO value for the statisticsSending property of the extended library configuration YMMYandexMetricaConfiguration.

// Creating an extended library configuration.
YMMYandexMetricaConfiguration *configuration = [[YMMYandexMetricaConfiguration alloc] initWithApiKey:@"API_key"];
// Disabling sending statistics.
configuration.statisticsSending = NO;
// Initializing the AppMetrica SDK.
[YMMYandexMetrica activateWithConfiguration:configuration];
Copied to clipboard
After the user has confirmed to send statistics (for example, in the application settings or in the agreement on the first start of the app), you should call the +setStatisticsSending: method of the YMMYandexMetrica class to enable it.
// Checking the status of the boolean variable. It shows the user confirmation.
if (flag) {
    // Enabling sending statistics.
    [YMMYandexMetrica setStatisticsSending:YES];
}
Copied to clipboard

Alert example

You can use any text to inform users of statistics collection. For example:

This app uses AppMetrica (Yandex.Metrica for applications) analytics provided by YANDEX LLC, 16, Leo Tolstoy St., Moscow, 119021, Russia (hereinafter referred to as “Yandex”) as specified in the Terms of Use of the service.

AppMetrica analyzes app usage data, including the device it is running on, the installation source, calculates conversion, collects statistics of your activity for product analytics, ad campaign analysis, and optimization, as well as for troubleshooting. Information collected in this way cannot identify you.

Depersonalized information about your use of this app collected by AppMetrica tools will be transferred to Yandex and stored on Yandex’s server in the EU and the Russian Federation. Yandex will process this information to assess how you use the app, compile reports for us on our app operation, and provide other services.