Usage examples
- Library initialization with the extended configuration
- Initializing the library for children's apps
- Sending statistics to an additional API key
- Tracking app crashes
- Determining the location
- Setting device location manually
- Sending a custom event
- Sending a custom event with nested parameters
- Sending an event from the WebView's JavaScript code
- Sending an error message
- Sending profile attributes
- Sending ProfileId
- Sending E-commerce events
- Sending Revenue
- Setting the length of the session timeout
- Setting the app version
- Tracking app openings using deeplinks
- Tracking new users
- Disable and enable sending statistics
Library initialization with the extended configuration
To initialize the library with the extended startup configuration:
- Initialize the YMMYandexMetricaConfiguration instance.
- Specify the configuration settings using methods of the
YMMYandexMetricaConfiguration
class. For example, enable logging or set a session timeout. - 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
To initialize the library with the extended startup configuration:
- Initialize the YMMYandexMetricaConfiguration instance.
- Specify the configuration settings using methods of the
YMMYandexMetricaConfiguration
class. For example, enable logging or set a session timeout. - Pass the
YMMYandexMetricaConfiguration
object to the activate(with:) method 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.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : AnyObject]? = nil) -> Bool { // Creating an extended library configuration. let configuration = YMMYandexMetricaConfiguration.init(apiKey: "API key") // Setting up the configuration. For example, to enable logging. configuration?.logs = true ... // Initializing the AppMetrica SDK. YMMYandexMetrica.activate(with: configuration!) return true }
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
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.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : AnyObject]? = nil) -> Bool { // Creating an extended library configuration. let configuration = YMMYandexMetricaConfiguration.init(apiKey: "API key") // Setting up the configuration. configuration?.appForKids = true ... // Initializing the AppMetrica SDK. YMMYandexMetrica.activate(with: configuration!) return true }
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
To initialize a reporter with an extended configuration:
- Initialize the YMMReporterConfiguration instance.
- Specify the configuration settings using methods of the
YMMReporterConfiguration
class. For example, enable logging or set a session timeout. - 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
To initialize a reporter with an extended configuration:
- Initialize the YMMReporterConfiguration instance.
- Specify the configuration settings using methods of the
YMMReporterConfiguration
class. For example, enable logging or set a session timeout. - Pass the
YMMReporterConfiguration
object to the activateReporter(with:) method 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. let reporterConfiguration = YMMReporterConfiguration.init(apiKey: "API key") // Setting up the configuration. For example, to enable logging. reporterConfiguration?.logs = true ... // Initializing a reporter. YMMYandexMetrica.activateReporter(with: reporterConfiguration!)
Copied to clipboard
Step 2. Configure sending data using a reporter
To send statistics data to another API key:
- 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.
- Use methods of the
YMMYandexMetricaReporting
protocol to send errors, events, and revenue. - 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
To send statistics data to another API key:
- 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.
- Use methods of the
YMMYandexMetricaReporting
protocol to send errors, events, and revenue. - To ensure that sessions are tracked correctly, set up sending session start and pause events for each reporter.
let reporter = YMMYandexMetrica.reporterForApiKey("API_key") reporter.resumeSession() ... reporter.reportEvent("Updates installed", onFailure: { (error) in print("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
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. let configuration = YMMYandexMetricaConfiguration.init(apiKey: "API_key") // Disabling sending the information on crashes of the application. configuration?.crashReporting = false // Initializing the AppMetrica SDK. YMMYandexMetrica.activate(with: configuration!)
Copied to clipboard
Determining the location
- 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
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 locationTracking disabled, set the locationTracking property of the YMMYandexMetricaConfiguration configuration to false
.
// Creating an extended library configuration. let configuration = YMMYandexMetricaConfiguration.init(apiKey: "API key") // Disabling sending information about the location of the device. configuration?.locationTracking = false // Initializing the AppMetrica SDK. YMMYandexMetrica.activate(with: configuration!)
Copied to clipboard
To disable locationTracking after initializing the library, use the method setLocationTracking(_:) of the YMMYandexMetrica class:
YMMYandexMetrica.setLocationTracking(false)
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.
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.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { YMMYandexMetrica.setLocation(locations.last) }
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
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, passnil
for this block.
[YMMYandexMetrica reportEvent:@"Updates installed" onFailure:^(NSError *error) { NSLog(@"DID FAIL REPORT EVENT: %@", message); NSLog(@"REPORT ERROR: %@", [error localizedDescription]); }];
Copied to clipboard
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, passnil
for this block.
YMMYandexMetrica.reportEvent("Updates installed", onFailure: { (error) in print("DID FAIL REPORT EVENT: %@", message) print("REPORT ERROR: %@", error?.localizedDescription) }
Copied to clipboard
Sending a custom event with nested parameters
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, passnil
for this block.
NSDictionary *params = @{@"key1": @"value1", @"key2": @"value2"}; [YMMYandexMetrica reportEvent:@"EVENT" parameters:params onFailure:^(NSError *error) { NSLog(@"error: %@", [error localizedDescription]); }];
Copied to clipboard
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, passnil
for this block.
let params : [AnyHashable : Any] = ["key1": "value1", "key2": "value2"] YMMYandexMetrica.reportEvent("EVENT", parameters: params, onFailure: { (error) in print("DID FAIL REPORT EVENT: %@", message) print("REPORT 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
let configuration = WKWebViewConfiguration() let userController = WKUserContentController() YMMYandexMetrica.initWebViewReporting(userController, onFailure: nil) userController.add(myHandler, name: myScriptName) configuration.userContentController = userController; let webView = WKWebView(frame: .zero, 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:
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
let firstError = NSError(domain: "com.yandex.error-a", code: 12, userInfo: [ YMMBacktraceErrorKey: Thread.callStackReturnAddresses, NSLocalizedDescriptionKey: "Error A" ]) YMMYandexMetrica.report(nserror: 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
let underlyingError = YMMError.init(identifier: "Underlying YMMError") let error = YMMError( identifier: "YMMError identifier", message: "Another custom message", parameters: [ "foo": "bar" ], backtrace: Thread.callStackReturnAddresses, underlyingError: underlyingError) YMMYandexMetrica.report(error: 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, passnil
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
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, passnil
for this block.
let profile = YMMMutableUserProfile() // Updating a single user profile attribute. let timeLeftAttribute: YMMCustomCounterAttribute = YMMProfileAttribute.customCounter("time_left") profile.apply(timeLeftAttribute.withDelta(-4.42)) // Updating multiple attributes. profile.apply(from: [ // Updating predefined attributes. YMMProfileAttribute.name().withValue("John"), YMMProfileAttribute.gender().withValue(YMMGenderType.male), YMMProfileAttribute.birthDate().withAge(24), YMMProfileAttribute.notificationsEnabled().withValue(false), // 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(true) ]) // ProfieID is set using the method of the YMMYandexMetrica class. YMMYandexMetrica.setUserProfileID("id") // Sending profile attributes. YMMYandexMetrica.report(profile, onFailure: { (error) in print("REPORT ERROR: %@", error.localizedDescription) })
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
To send a 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):
// 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];
// 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
// 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
// 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
// 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
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 (Swift):
// Creating a screen object.
let screen = YMMECommerceScreen(
name: "ProductCardScreen",
categoryComponents: ["Акции", "Красная цена"],
searchQuery: "даниссимо кленовый сироп",
payload: ["full_screen": "true"]
)
// Sending an e-commerce event.
YMMYandexMetrica.report(eCommerce: .showScreenEvent(screen: screen), onFailure: nil)
// Creating a screen object. let screen = YMMECommerceScreen( name: "ProductCardScreen", categoryComponents: ["Акции", "Красная цена"], searchQuery: "даниссимо кленовый сироп", payload: ["full_screen": "true"] ) // Creating an actualPrice object. let actualPrice = YMMECommercePrice( fiat: .init(unit: "USD", value: .init(string: "4.53")), internalComponents: [ .init(unit: "wood", value: .init(string: "30570000")), .init(unit: "iron", value: .init(string: "26.89")), .init(unit: "gold", value: .init(string: "5.1")), ] ) // Creating a product object. let product = YMMECommerceProduct( sku: "779213", name: "Продукт творожный «Даниссимо» 5.9%, 130 г.", categoryComponents: ["Продукты", "Молочные продукты", "Йогурты"], payload: ["full_screen": "true"], actualPrice: actualPrice, originalPrice: .init( fiat: .init(unit: "USD", value: .init(string: "5.78")), internalComponents: [ .init(unit: "wood", value: .init(string: "30590000")), .init(unit: "iron", value: .init(string: "26.92")), .init(unit: "gold", value: .init(string: "5.5")), ] ), promoCodes: ["BT79IYX", "UT5412EP"] ) // Sending an e-commerce event. YMMYandexMetrica.report(eCommerce: .showProductCardEvent(product: product, screen: screen), onFailure: nil)
Copied to clipboard
// Creating a screen object. let screen = YMMECommerceScreen( name: "ProductCardScreen", categoryComponents: ["Акции", "Красная цена"], searchQuery: "даниссимо кленовый сироп", payload: ["full_screen": "true"] ) // Creating an actualPrice object. let actualPrice = YMMECommercePrice( fiat: .init(unit: "USD", value: .init(string: "4.53")), internalComponents: [ .init(unit: "wood", value: .init(string: "30570000")), .init(unit: "iron", value: .init(string: "26.89")), .init(unit: "gold", value: .init(string: "5.1")), ] ) // Creating a product object. let product = YMMECommerceProduct( sku: "779213", name: "Продукт творожный «Даниссимо» 5.9%, 130 г.", categoryComponents: ["Продукты", "Молочные продукты", "Йогурты"], payload: ["full_screen": "true"], actualPrice: actualPrice, originalPrice: .init( fiat: .init(unit: "USD", value: .init(string: "5.78")), internalComponents: [ .init(unit: "wood", value: .init(string: "30590000")), .init(unit: "iron", value: .init(string: "26.92")), .init(unit: "gold", value: .init(string: "5.5")), ] ), promoCodes: ["BT79IYX", "UT5412EP"] ) // Creating a referrer object. let referrer = YMMECommerceReferrer(type: "button", identifier: "76890", screen: screen) // Sending an e-commerce event. YMMYandexMetrica.report(eCommerce: .showProductDetailsEvent(product: product, referrer: referrer), onFailure: nil)
Copied to clipboard
// Creating a screen object. let screen = YMMECommerceScreen( name: "ProductCardScreen", categoryComponents: ["Акции", "Красная цена"], searchQuery: "даниссимо кленовый сироп", payload: ["full_screen": "true"] ) // Creating an actualPrice object. let actualPrice = YMMECommercePrice( fiat: .init(unit: "USD", value: .init(string: "4.53")), internalComponents: [ .init(unit: "wood", value: .init(string: "30570000")), .init(unit: "iron", value: .init(string: "26.89")), .init(unit: "gold", value: .init(string: "5.1")), ] ) // Creating a product object. let product = YMMECommerceProduct( sku: "779213", name: "Продукт творожный «Даниссимо» 5.9%, 130 г.", categoryComponents: ["Продукты", "Молочные продукты", "Йогурты"], payload: ["full_screen": "true"], actualPrice: actualPrice, originalPrice: .init( fiat: .init(unit: "USD", value: .init(string: "5.78")), internalComponents: [ .init(unit: "wood", value: .init(string: "30590000")), .init(unit: "iron", value: .init(string: "26.92")), .init(unit: "gold", value: .init(string: "5.5")), ] ), promoCodes: ["BT79IYX", "UT5412EP"] ) // Creating a referrer object. let referrer = YMMECommerceReferrer(type: "button", identifier: "76890", screen: screen) // Creating a cartItem object. let addedItems = YMMECommerceCartItem( product: product, referrer: referrer, quantity: .init(string: "1"), revenue: actualPrice ) // Sending an e-commerce event. YMMYandexMetrica.report(eCommerce: .addCartItemEvent(cartItem: addedItems), onFailure: nil) // Or: YMMYandexMetrica.report(eCommerce: .removeCartItemEvent(cartItem: addedItems), onFailure: nil)
Copied to clipboard
// Creating a screen object. let screen = YMMECommerceScreen( name: "ProductCardScreen", categoryComponents: ["Акции", "Красная цена"], searchQuery: "даниссимо кленовый сироп", payload: ["full_screen": "true"] ) // Creating an actualPrice object. let actualPrice = YMMECommercePrice( fiat: .init(unit: "USD", value: .init(string: "4.53")), internalComponents: [ .init(unit: "wood", value: .init(string: "30570000")), .init(unit: "iron", value: .init(string: "26.89")), .init(unit: "gold", value: .init(string: "5.1")), ] ) // Creating a product object. let product = YMMECommerceProduct( sku: "779213", name: "Продукт творожный «Даниссимо» 5.9%, 130 г.", categoryComponents: ["Продукты", "Молочные продукты", "Йогурты"], payload: ["full_screen": "true"], actualPrice: actualPrice, originalPrice: .init( fiat: .init(unit: "USD", value: .init(string: "5.78")), internalComponents: [ .init(unit: "wood", value: .init(string: "30590000")), .init(unit: "iron", value: .init(string: "26.92")), .init(unit: "gold", value: .init(string: "5.5")), ] ), promoCodes: ["BT79IYX", "UT5412EP"] ) // Creating a referrer object. let referrer = YMMECommerceReferrer(type: "button", identifier: "76890", screen: screen) // Creating a cartItem object. let addedItems = YMMECommerceCartItem( product: product, referrer: referrer, quantity: .init(string: "1"), revenue: actualPrice ) // Creating an order object. let order = YMMECommerceOrder( identifier: "88528768", cartItems: [addedItems], payload: ["black_friday": "true"] ) // Sending an e-commerce event. YMMYandexMetrica.report(eCommerce: .beginCheckoutEvent(order:order), onFailure: nil) YMMYandexMetrica.report(eCommerce: .purchaseEvent(order: 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 an e-commerce event. YMMYandexMetrica.report(eCommerce: .showScreenEvent(screen: 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.
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:
- Initialize the YMMMutableRevenueInfo instance.
- To validate a purchase, specify transactionID and receiptData. You should receive them before invoking
[[SKPaymentQueue defaultQueue] finishTransaction:transaction]
. - 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
To send information about a purchase:
- Initialize the YMMMutableRevenueInfo instance.
- (Optional) To group purchases by OrderID, specify it in the payload property.Note. If the OrderID is not specified, AppMetrica generates the ID automatically.
- 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.
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; // Setting the OrderID parameter in the payload property to group purchases revenueInfo.payload = @{ @"OrderID": @"Identifier", @"source": @"AppStore" }; // 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); }];
Copied to clipboard
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:
- Initialize the YMMMutableRevenueInfo instance.
- To validate a purchase, specify transactionID and receiptData. You should receive them before invoking
[[SKPaymentQueue defaultQueue] finishTransaction:transaction]
. - 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.
func completeTransaction(_ transaction: SKPaymentTransaction) { ... let price = NSDecimalNumber(string: "2100.5") // Initializing the Revenue instance. let revenueInfo = YMMMutableRevenueInfo.init(priceDecimal: price, currency: "BYN") revenueInfo.productID = "TV soundbar" revenueInfo.quantity = 2 revenueInfo.payload = ["source": "AppStore"] // Set purchase information for validation. if let url = Bundle.main.appStoreReceiptURL, let data = try? Data(contentsOf: url), let transactionID = transaction.transactionIdentifier { revenueInfo.transactionID = transactionID revenueInfo.receiptData = data } // Sending the Revenue instance using reporter. let reporter = YMMYandexMetrica.reporterForApiKey("API_key") reporter.reportRevenue(revenueInfo, onFailure: { (error) in print("REPORT ERROR: \(error.localizedDescription)") }) // Remove the transaction from the payment queue. SKPaymentQueue.default().finishTransaction(transaction) }
Copied to clipboard
To send information about a purchase:
- Initialize the YMMMutableRevenueInfo instance.
- (Optional) To group purchases by OrderID, specify it in the payload property.Note. If the OrderID is not specified, AppMetrica generates the ID automatically.
- 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.
let price = NSDecimalNumber(string: "2100.5") // Initializing the Revenue instance. let revenueInfo = YMMMutableRevenueInfo.init(priceDecimal: price, currency: "BYN") revenueInfo.productID = "TV soundbar" revenueInfo.quantity = 2 // To group purchases, set the OrderID parameter in the payload property. revenueInfo.payload = ["OrderID": "Identifier", "source": "AppStore"] // Sending the Revenue instance using reporter. let reporter = YMMYandexMetrica.reporterForApiKey("API_key") reporter.reportRevenue(revenueInfo, onFailure: { (error) in print("REPORT ERROR: \(error.localizedDescription)") })
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
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
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. let configuration = YMMYandexMetricaConfiguration.init(apiKey: "API key") // Setting the session timeout. configuration?.sessionTimeout = 15 // Initializing the AppMetrica SDK. YMMYandexMetrica.activate(with: 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
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. let configuration = YMMYandexMetricaConfiguration.init(apiKey: "API key") // Setting the app version. configuration?.appVersion = "1.13.2" // Initializing the AppMetrica SDK. YMMYandexMetrica.activate(with: 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.
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; }
Copied to clipboard
You need to track app openings to correctly track remarketing campaigns.
To track app openings via deeplinks or Universal Links, use the handleOpen(_:) method of the YMMYandexMetrica class.
To track app openings using a deeplink, make the following changes in UIApplicationDelegate
:
func application(_ application: UIApplication, handleOpenURL url: URL) -> Bool { return YMMYandexMetrica.handleOpen(url) } func application(_ application: UIApplication, openURL url: URL, sourceApplication: String?, annotation: AnyObject) -> Bool { return YMMYandexMetrica.handleOpen(url) } // Delegate for tracking Universal links. func application(_ application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool { if userActivity.activityType == NSUserActivityTypeBrowsingWeb { if let url = userActivity.webpageURL { YMMYandexMetrica.handleOpen(url) } } return true }
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
var isFirstLaunch = false // Creating an extended library configuration. let configuration = YMMYandexMetricaConfiguration.init(apiKey: "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 = true } configuration?.handleFirstActivationAsUpdate = !isFirstLaunch // Initializing the AppMetrica SDK. YMMYandexMetrica.activate(with: 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
// Checking the status of the boolean variable. It shows the user confirmation. if (flag) { // Enabling sending statistics. [YMMYandexMetrica setStatisticsSending:YES]; }
Copied to clipboard
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. let configuration = YMMYandexMetricaConfiguration.init(apiKey: "API key") // Disabling sending statistics. configuration?.statisticsSending = false // Initializing the AppMetrica SDK. YMMYandexMetrica.activate(with: configuration!)
Copied to clipboard
// Checking the status of the boolean variable. It shows the user confirmation. if flag { // Enabling sending statistics. YMMYandexMetrica.setStatisticsSending(true); }
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.