Usage examples

Library initialization 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

Initializing the library for children's apps

If you have an app for kids, use the appForKids property of the YMMYandexMetricaConfiguration configuration. This property defines the application type as “children's” to match the rules for checking children's apps.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Creating an extended library configuration.
    YMMYandexMetricaConfiguration *configuration = [[YMMYandexMetricaConfiguration alloc] initWithApiKey:@"API_key"];
    // Setting up the configuration.
    configuration.appForKids = YES;
    ...
    // Initializing the AppMetrica SDK.
    [YMMYandexMetrica activateWithConfiguration:configuration];
}
Copied to clipboard
Note. If this option is enabled, the AppMetrica SDK doesn't send advertising IDs or location information.

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

Tracking 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

AppMetrica can determine the location of a device. Location accuracy depends on the configuration that the library uses for initialization:
With the locationTracking option enabled
Note.

For iOS, the option is enabled by default.

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
Note.

Starting with the Android AppMetrica SDK 5.0.0, the locationTracking option is disabled by default.

If the version is lower than 5.0.0, the locationTracking option is enabled by default.

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 locationTracking enabled, but it doesn't request permission to get 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 about the device location, make sure that reporting is enabled.

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 event from the WebView's JavaScript code

The AppMetrica SDK lets you send client events from JavaScript code. Initialize the sending by calling the initWebViewReporting method(Objective-C, Swift):

WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKUserContentController *userController = [[WKUserContentController alloc] init];
[YMMYandexMetrica initWebViewReporting:userController onFailure:nil];
[userController addScriptMessageHandler:myHandler name:myScriptName];
configuration.userContentController = userController;
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
Copied to clipboard

Call this method before loading any content. We recommend calling this method before creating a webview and before adding your scripts to WKUserContentController.

To send an event from JavaScript code, use the reportEvent(name, value) method in the AppMetrica interface:

function buttonClicked() {
  AppMetrica.reportEvent('Button clicked!', '{}');
})
Copied to clipboard

Arguments of the reportEvent method:

  • name — A string. Can't be null or empty.
  • value — A JSON string. Can be null.

Sending an error message

To send your own error message, use the YMMYandexMetrica class and YMMYandexMetricaReporting protocol methods:

Note. These methods are supported since AppMetrica SDK version 3.11.1.

To send error messages, you can use the standard NSError class, the simplified YMMError class, or the YMMErrorRepresentable protocol.

Example with NSError

If errors are sent using the NSError class, they're grouped by the domain domain and the code error code.

NSError *firstError = [NSError errorWithDomain:@"com.yandex.error-a"
                                          code:12
                                      userInfo:@{
                                          YMMBacktraceErrorKey: NSThread.callStackReturnAddresses,
                                          NSLocalizedDescriptionKey: @"Error A"
                                      }];
[YMMYandexMetrica reportNSError:firstError onFailure:nil];
Copied to clipboard

Example with YMMError

If errors are sent using the YMMError class or the YMMErrorRepresentable protocol, they're grouped by the identifier ID.

YMMError *underlyingError = [YMMError errorWithIdentifier:@"Underlying YMMError"];
YMMError *error = [YMMError errorWithIdentifier:@"YMMError identifier"
                                        message:@"Another custom message"
                                     parameters:@{ @"foo": @"bar" }
                                      backtrace:NSThread.callStackReturnAddresses
                                underlyingError:underlyingError];
[YMMYandexMetrica reportError:error onFailure:nil];
Copied to clipboard

Don't use variable values as grouping IDs. Otherwise, the number of groups increases and it becomes difficult to analyze them.

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 E-commerce events

“”“”In AppMetrica, it is not possible to segment E-commerce events into test and not test. If you use the main API key for debugging purchases, the test events are included in general statistics. If you need to debug sending E-commerce events, use a reporter to send statistics to an additional API key.

Step 1. Configure sending E-commerce events to the test API key

For different user actions, there are appropriate types of E-commerce events. To create a specific event type, use the appropriate YMMECommerce class method.

The examples below show how to send specific types of events (Objective-C):

Opening a page
// Creating a screen object. 
YMMECommerceScreen *screen = [[YMMECommerceScreen alloc] initWithName:@"ProductCardScreen"
                                                   categoryComponents:@[ @"Акции", @"Красная цена" ]
                                                          searchQuery:@"даниссимо кленовый сироп"
                                                              payload:@{ @"full_screen": @"true" }];
// Sending an e-commerce event.
id<YMMYandexMetricaReporting> reporter = [YMMYandexMetrica reporterForApiKey:@"Testing API key"];
[reporter reportECommerce:[YMMECommerce showScreenEventWithScreen:screen] onFailure:nil];
Viewing a product profile
// Creating a screen object. 
YMMECommerceScreen *screen = [[YMMECommerceScreen alloc] initWithName:@"ProductCardScreen"
                                                   categoryComponents:@[ @"Акции", @"Красная цена" ]
                                                          searchQuery:@"даниссимо кленовый сироп"
                                                              payload:@{ @"full_screen": @"true" }];
// Creating an actualPrice object.
YMMECommerceAmount *actualFiat =
        [[YMMECommerceAmount alloc] initWithUnit:@"USD" value:[NSDecimalNumber decimalNumberWithString:@"4.53"]];
YMMECommerceAmount *woodActualPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"wood" value:[NSDecimalNumber decimalNumberWithString:@"30570000"]];
YMMECommerceAmount *ironActualPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"iron" value:[NSDecimalNumber decimalNumberWithString:@"26.89"]];
YMMECommerceAmount *goldActualPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"gold" value:[NSDecimalNumber decimalNumberWithString:@"5.1"]];
YMMECommercePrice *actualPrice = [[YMMECommercePrice alloc] initWithFiat:actualFiat
                                                      internalComponents:@[ woodActualPrice, ironActualPrice, goldActualPrice ]];
// Creating an originalPrice object.
YMMECommerceAmount *originalFiat =
        [[YMMECommerceAmount alloc] initWithUnit:@"USD" value:[NSDecimalNumber decimalNumberWithString:@"5.78"]];
YMMECommerceAmount *woodOriginalPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"wood" value:[NSDecimalNumber decimalNumberWithString:@"30590000"]];
YMMECommerceAmount *ironOriginalPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"iron" value:[NSDecimalNumber decimalNumberWithString:@"26.92"]];
YMMECommerceAmount *goldOriginalPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"gold" value:[NSDecimalNumber decimalNumberWithString:@"5.5"]];
YMMECommercePrice *originalPrice = [[YMMECommercePrice alloc] initWithFiat:originalFiat
                                                        internalComponents:@[ woodOriginalPrice, ironOriginalPrice, goldOriginalPrice ]];
// Creating a product object.
YMMECommerceProduct *product = [[YMMECommerceProduct alloc] initWithSKU:@"779213"
                                                                   name:@"Продукт творожный «Даниссимо» 5.9%, 130 г."
                                                     categoryComponents:@[ @"Продукты", @"Молочные продукты", @"Йогурты" ]
                                                                payload:@{ @"full_screen" : @"true" }
                                                            actualPrice:actualPrice
                                                          originalPrice:originalPrice
                                                             promoCodes:@[ @"BT79IYX", @"UT5412EP" ]];
// Sending an e-commerce event.
id<YMMYandexMetricaReporting> reporter = [YMMYandexMetrica reporterForApiKey:@"Testing API key"];
[reporter reportECommerce:[YMMECommerce showProductCardEventWithProduct:product screen:screen] onFailure:nil];
Copied to clipboard
Viewing a product page
// Creating a screen object. 
YMMECommerceScreen *screen = [[YMMECommerceScreen alloc] initWithName:@"ProductCardScreen"
                                                   categoryComponents:@[ @"Акции", @"Красная цена" ]
                                                          searchQuery:@"даниссимо кленовый сироп"
                                                              payload:@{ @"full_screen": @"true" }];

// Creating an actualPrice object.
YMMECommerceAmount *actualFiat =
        [[YMMECommerceAmount alloc] initWithUnit:@"USD" value:[NSDecimalNumber decimalNumberWithString:@"4.53"]];
YMMECommerceAmount *woodActualPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"wood" value:[NSDecimalNumber decimalNumberWithString:@"30570000"]];
YMMECommerceAmount *ironActualPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"iron" value:[NSDecimalNumber decimalNumberWithString:@"26.89"]];
YMMECommerceAmount *goldActualPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"gold" value:[NSDecimalNumber decimalNumberWithString:@"5.1"]];
YMMECommercePrice *actualPrice = [[YMMECommercePrice alloc] initWithFiat:actualFiat
                                                      internalComponents:@[ woodActualPrice, ironActualPrice, goldActualPrice ]];
// Creating an originalPrice object.
YMMECommerceAmount *originalFiat =
        [[YMMECommerceAmount alloc] initWithUnit:@"USD" value:[NSDecimalNumber decimalNumberWithString:@"5.78"]];
YMMECommerceAmount *woodOriginalPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"wood" value:[NSDecimalNumber decimalNumberWithString:@"30590000"]];
YMMECommerceAmount *ironOriginalPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"iron" value:[NSDecimalNumber decimalNumberWithString:@"26.92"]];
YMMECommerceAmount *goldOriginalPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"gold" value:[NSDecimalNumber decimalNumberWithString:@"5.5"]];
YMMECommercePrice *originalPrice = [[YMMECommercePrice alloc] initWithFiat:originalFiat
                                                        internalComponents:@[ woodOriginalPrice, ironOriginalPrice, goldOriginalPrice ]];
// Creating a product object.
YMMECommerceProduct *product = [[YMMECommerceProduct alloc] initWithSKU:@"779213"
                                                                   name:@"Продукт творожный «Даниссимо» 5.9%, 130 г."
                                                     categoryComponents:@[ @"Продукты", @"Молочные продукты", @"Йогурты" ]
                                                                payload:@{ @"full_screen" : @"true" }
                                                            actualPrice:actualPrice
                                                          originalPrice:originalPrice
                                                             promoCodes:@[ @"BT79IYX", @"UT5412EP" ]];
// Creating a referrer object.
YMMECommerceReferrer *referrer = [[YMMECommerceReferrer alloc] initWithType:@"button"
                                                                 identifier:@"76890"
                                                                     screen:screen];
// Sending an e-commerce event.
id<YMMYandexMetricaReporting> reporter = [YMMYandexMetrica reporterForApiKey:@"Testing API key"];
[reporter reportECommerce:[YMMECommerce showProductDetailsEventWithProduct:product referrer:referrer] onFailure:nil];
Copied to clipboard
Adding or removing an item to/from the cart
// Creating a screen object. 
YMMECommerceScreen *screen = [[YMMECommerceScreen alloc] initWithName:@"ProductCardScreen"
                                                   categoryComponents:@[ @"Акции", @"Красная цена" ]
                                                          searchQuery:@"даниссимо кленовый сироп"
                                                              payload:@{ @"full_screen": @"true" }];
// Creating an actualPrice object.
YMMECommerceAmount *actualFiat =
        [[YMMECommerceAmount alloc] initWithUnit:@"USD" value:[NSDecimalNumber decimalNumberWithString:@"4.53"]];
YMMECommerceAmount *woodActualPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"wood" value:[NSDecimalNumber decimalNumberWithString:@"30570000"]];
YMMECommerceAmount *ironActualPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"iron" value:[NSDecimalNumber decimalNumberWithString:@"26.89"]];
YMMECommerceAmount *goldActualPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"gold" value:[NSDecimalNumber decimalNumberWithString:@"5.1"]];
YMMECommercePrice *actualPrice = [[YMMECommercePrice alloc] initWithFiat:actualFiat
                                                      internalComponents:@[ woodActualPrice, ironActualPrice, goldActualPrice ]];
// Creating an originalPrice object.
YMMECommerceAmount *originalFiat =
        [[YMMECommerceAmount alloc] initWithUnit:@"USD" value:[NSDecimalNumber decimalNumberWithString:@"5.78"]];
YMMECommerceAmount *woodOriginalPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"wood" value:[NSDecimalNumber decimalNumberWithString:@"30590000"]];
YMMECommerceAmount *ironOriginalPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"iron" value:[NSDecimalNumber decimalNumberWithString:@"26.92"]];
YMMECommerceAmount *goldOriginalPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"gold" value:[NSDecimalNumber decimalNumberWithString:@"5.5"]];
YMMECommercePrice *originalPrice = [[YMMECommercePrice alloc] initWithFiat:originalFiat
                                                        internalComponents:@[ woodOriginalPrice, ironOriginalPrice, goldOriginalPrice ]];
// Creating a product object.
YMMECommerceProduct *product = [[YMMECommerceProduct alloc] initWithSKU:@"779213"
                                                                   name:@"Продукт творожный «Даниссимо» 5.9%, 130 г."
                                                     categoryComponents:@[ @"Продукты", @"Молочные продукты", @"Йогурты" ]
                                                                payload:@{ @"full_screen" : @"true" }
                                                            actualPrice:actualPrice
                                                          originalPrice:originalPrice
                                                             promoCodes:@[ @"BT79IYX", @"UT5412EP" ]];
// Creating a referrer object.
YMMECommerceReferrer *referrer = [[YMMECommerceReferrer alloc] initWithType:@"button"
                                                                 identifier:@"76890"
                                                                     screen:screen];
// Creating a cartItem object.
NSDecimalNumber *quantity = [NSDecimalNumber decimalNumberWithString:@"1"];
YMMECommerceCartItem *addedItems = [[YMMECommerceCartItem alloc] initWithProduct:product
                                                                      referrer:referrer
                                                                      quantity:quantity
                                                                       revenue:actualPrice];
// Sending an e-commerce event.
id<YMMYandexMetricaReporting> reporter = [YMMYandexMetrica reporterForApiKey:@"Testing API key"];
[reporter reportECommerce:[YMMECommerce addCartItemEvent:addedItems] onFailure:nil];
// Or:
[YMMYandexMetrica reportECommerce:[YMMECommerce removeCartItemEventWithItem:addedItems] onFailure:nil];
Copied to clipboard
Starting and completing a purchase
// Creating a screen object. 
YMMECommerceScreen *screen = [[YMMECommerceScreen alloc] initWithName:@"ProductCardScreen"
                                                   categoryComponents:@[ @"Акции", @"Красная цена" ]
                                                          searchQuery:@"даниссимо кленовый сироп"
                                                              payload:@{ @"full_screen": @"true" }];
// Creating an actualPrice object.
YMMECommerceAmount *actualFiat =
        [[YMMECommerceAmount alloc] initWithUnit:@"USD" value:[NSDecimalNumber decimalNumberWithString:@"4.53"]];
YMMECommerceAmount *woodActualPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"wood" value:[NSDecimalNumber decimalNumberWithString:@"30570000"]];
YMMECommerceAmount *ironActualPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"iron" value:[NSDecimalNumber decimalNumberWithString:@"26.89"]];
YMMECommerceAmount *goldActualPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"gold" value:[NSDecimalNumber decimalNumberWithString:@"5.1"]];
YMMECommercePrice *actualPrice = [[YMMECommercePrice alloc] initWithFiat:actualFiat
                                                      internalComponents:@[ woodActualPrice, ironActualPrice, goldActualPrice ]];
// Creating an originalPrice object.
YMMECommerceAmount *originalFiat =
        [[YMMECommerceAmount alloc] initWithUnit:@"USD" value:[NSDecimalNumber decimalNumberWithString:@"5.78"]];
YMMECommerceAmount *woodOriginalPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"wood" value:[NSDecimalNumber decimalNumberWithString:@"30590000"]];
YMMECommerceAmount *ironOriginalPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"iron" value:[NSDecimalNumber decimalNumberWithString:@"26.92"]];
YMMECommerceAmount *goldOriginalPrice =
        [[YMMECommerceAmount alloc] initWithUnit:@"gold" value:[NSDecimalNumber decimalNumberWithString:@"5.5"]];
YMMECommercePrice *originalPrice = [[YMMECommercePrice alloc] initWithFiat:originalFiat
                                                        internalComponents:@[ woodOriginalPrice, ironOriginalPrice, goldOriginalPrice ]];
// Creating a product object.
YMMECommerceProduct *product = [[YMMECommerceProduct alloc] initWithSKU:@"779213"
                                                                   name:@"Продукт творожный «Даниссимо» 5.9%, 130 г."
                                                     categoryComponents:@[ @"Продукты", @"Молочные продукты", @"Йогурты" ]
                                                                payload:@{ @"full_screen" : @"true" }
                                                            actualPrice:actualPrice
                                                          originalPrice:originalPrice
                                                             promoCodes:@[ @"BT79IYX", @"UT5412EP" ]];
// Creating a referrer object.
YMMECommerceReferrer *referrer = [[YMMECommerceReferrer alloc] initWithType:@"button"
                                                                 identifier:@"76890"
                                                                     screen:screen];
// Creating a cartItem object.
NSDecimalNumber *quantity = [NSDecimalNumber decimalNumberWithString:@"1"];
YMMECommerceCartItem *addedItems = [[YMMECommerceCartItem alloc] initWithProduct:product
                                                                      referrer:referrer
                                                                      quantity:quantity
                                                                       revenue:actualPrice];
// Creating an order object.
YMMECommerceOrder *order = [[YMMECommerceOrder alloc] initWithIdentifier:@"88528768"
                                                               cartItems:@[ addedItems ]
                                                                 payload:@{ @"black_friday" : @"true"}];
// Sending an e-commerce event.
id<YMMYandexMetricaReporting> reporter = [YMMYandexMetrica reporterForApiKey:@"Testing API key"];
[reporter reportECommerce:[YMMECommerce beginCheckoutEventWithOrder:order] onFailure:nil];
[YMMYandexMetrica reportECommerce:[YMMECommerce purchaseEventWithOrder:order] onFailure:nil];
Copied to clipboard

Step 2. Check the test application's report

Make in-app test purchases. After a while, check the “Purchase analysis” report in the AppMetrica interface. Make sure that the report shows E-commerce events.

For more information about the report, see Purchase analysis.

Step 3. Configure sending events to the main API key

After successful testing, configure sending E-commerce events to the main API key.

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

...
// Sending an e-commerce event.
[YMMYandexMetrica reportECommerce:[YMMECommerce showScreenEventWithScreen:screen] onFailure:nil];
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, this purchase isn't shown in reports.

Note. To validate purchases, enable the validation in the settings. For more information, see Sending In-App purchases 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. If you need to debug sending Revenue, use a reporter to send statistics to an 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, onFailure: { error in
    print("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 using deeplinks

You need to track app openings to correctly track 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, when the app is first launched, all users are identified as new. If the AppMetrica SDK connects to an app that already has active users, you can configure it for new and old users to track statistics correctly. 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.handleFirstActivationAsUpdate = !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 the AppMetrica analytical service (Yandex Metrica for apps) provided by YANDEX LLC, ulitsa Lva Tolstogo 16, Moscow, Russia 119021 (hereinafter referred to as Yandex) based on the Terms of Use.

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.

If you didn't find the answer you were looking for, you can use the feedback form to submit your question. Please describe the problem in as much detail as possible. Attach a screenshot if possible.