Usage examples

Initializing the library with the extended configuration

To initialize the library with the extended startup configuration, pass to the method
[YMMYandexMetrica activateWithConfiguration:(YMMYandexMetricaConfiguration *)configuration];
the instance of the YMMYandexMetricaConfiguration class with the necessary settings. The extended configuration allows you to enable/disable logging, set session timeout, pass parameters for tracking pre-installed apps, and so on.

The parameters of the extended configuration are applied from the time of library initialization.

- (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 copy]];
}

To configure the library while the application is running, use the methods of the YMMYandexMetrica class.

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.

To initialize a reporter with the extended configuration, pass to the method
[YMMYandexMetrica activateReporterWithConfiguration:(YMMReporterConfiguration *)configuration];
the instance of the YMMReporterConfiguration class with the necessary settings. This configuration is used for a reporter with the specified API key. You can set up your own configuration for each additional API key.
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.
// 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]];
To send data using a reporter, you must get an object that implements the YMMYandexMetricaReporting protocol using the method [YMMYandexMetrica reporterForApiKey:(NSString *)apiKey];

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

The received object can be used to send reports by using methods of the YMMYandexMetricaReporting protocol.

Example of sending an event:

YMMYandexMetricaReporting reporting = [YMMYandexMetrica reporterForApiKey:API_key];
[reporting reportEvent:@"Updates installed" onFailure:^(NSError *error) {
    NSLog(@"DID FAIL REPORT EVENT: %@", message);
    NSLog(@"REPORT ERROR: %@", [error localizedDescription]);
}];

For correct tracking, the reporters should be manually configured to send events about the start and the pause of the session for each reporter.

YMMYandexMetricaReporting reporting = [YMMYandexMetrica reporterForApiKey:API_key];
[reporting resumeSession];
...
[reporting reportEvent:@"Updates installed" onFailure:^(NSError *error) {
    NSLog(@"DID FAIL REPORT EVENT: %@", message);
    NSLog(@"REPORT ERROR: %@", [error localizedDescription]);
}];
...
[reporting pauseSession];
Note. The session will be terminated if the application is restarted.

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 BOOL 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 copy]];

Sending the device location by the library

By default, sending the device location in library reports is enabled.
Attention. AppMetrica SDK does not request the permission for getting location data. You should implement this using the methods of the CLLocationManager class at the appropriate time.

AppMetrica allows you to manage sending reports about the device location. When you disable sending the user location, it also turns off all other methods to locate the device (including locating by IP address) in the AppMetrica SDK. Users who have the option to send location data disabled are grouped together in the geographic report with the “Undefined” value as the region name.

The option to send location data is enabled by default.

To disable sending, initialize the library with the configuration where sending device location option is disabled. To do this, set the NO value for the locationTracking property of the extended library configuration YMMYandexMetricaConfiguration.
// 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 copy]];

To disable sending while the app is running, use the method + (void)setLocationTracking: (BOOL)enabled of the YMMYandexMetrica class.

[YMMYandexMetrica setTrackLocationEnabled:NO];

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 your own device location information, pass an instance of the CLLocation class into the [YMMYandexMetrica setLocation:(CLLocation *)location]; method.

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

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

Sending a custom event

To send your custom event without nested parameters, pass to the method

[YMMYandexMetrica reportEvent:(NSString *)message
                    onFailure:(void (^)(NSError *error))onFailure];
the following parameters:
  • 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]);
}];

Sending a custom event with nested parameters

To send your custom event without nested parameters, pass to the method
[YMMYandexMetrica reportEvent:(NSString *)message
                   parameters:(NSDictionary *)params
                    onFailure:(void (^)(NSError *error))onFailure];
the following parameters:
  • message — Short name or description of the event;
  • params — Nested parameters as “key-value” pairs;
  • 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]);
                    }];

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.

For more information about events, see Add your own events.

Sending an error message

To send a custom error message, pass to the method
[YMMYandexMetrica reportError:(NSString *)message
                    exception:(NSException *)exception
                      failure:(NSError * __ autoreleasing *)onFailure];
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];
}

Sending profile attributes

To send profile attributes, pass to the method

[YMMYandexMetrica reportUserProfile:(YMMUserProfile *)userProfile
                          onFailure:(void (^)(NSError *error))onFailure];

the following parameters:

  • userProfile — An object 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);
}];

Setting the length of the session timeout

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

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

// 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 copy]];

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 copy]];

where 1.13.2 is the app version.

Tracking app openings via deeplinks

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

Note. To work with Universal Links, configure them for your application.

To track app openings that use deeplinks and Universal Links, use the +handleOpenURL: method:

To track app openings using a deeplink, make the following changes in UIApplicationDelegate:

- (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;
}

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 copy]];

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 BOOL 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 copy]];

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 + (void)setStatisticsSending:(BOOL)enabled 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];
}