Usage examples

Initializing the library with the extended configuration

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

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

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

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

Sending statistics to an additional API key

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

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

To initialize a reporter with the extended configuration, pass to the method
YMMYandexMetrica.activateReporterWithConfiguration(_ configuration: YMMReporterConfiguration)
the instance of the YMMReporterConfiguration class with the necessary settings. This configuration is used for a reporter with the specified API key. You can set up your own configuration for each additional API key.
Attention. The reporter with the extended configuration should be initialized before the first call to the reporter. Otherwise, the reporter will be initialized without a configuration.
// Creating an extended library configuration.
let reporterConfiguration = YMMReporterConfiguration.init(apiKey: "API key")
// Setting up the configuration. For example, to enable logging.
reporterConfiguration?.logs = true
...
// Initializing the AppMetrica SDK.
YMMYandexMetrica.activateReporterWithConfiguration(reporterConfiguration!)
Copied to clipboard
To send data using a reporter, you must get an object that implements the YMMReporterConfiguration protocol using the method
YMMYandexMetrica.reporterForApiKey(_ apiKey: String) -> YMMYandexMetricaReporting?

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

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

Example of sending reports:

let reporter = YMMYandexMetrica.reporterForApiKey("API_key")
reporter.reportEvent("Updates installed") { (error) in
    print("REPORT ERROR: %@", error?.localizedDescription)
}
Copied to clipboard

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

let reporter = YMMYandexMetrica.reporterForApiKey("API_key")
reporter.resumeSession()
...
reporter.reportEvent("Updates installed") { (error) in
    print("REPORT ERROR: %@", error?.localizedDescription)
}
...
reporter.pauseSession()
Copied to clipboard
Note. The session will be terminated if the application is restarted.

Monitoring app crashes

Reports on app crashes are sent by default.

To disable automatic monitoring, initialize the library with the configuration in which sending crashes is disabled. To do this, set the false 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 emergency stops of the application.
configuration?.crashReporting = false
// Initializing the AppMetrica SDK.
YMMYandexMetrica.activate(with: configuration!)
Copied to clipboard

Sending the device location by the library

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

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

The option to send location data is enabled by default.

To disable sending, initialize the library with the configuration where sending device location option is disabled. To do this, set the false value for the locationTracking property of the extended library configuration YMMYandexMetricaConfiguration.
// 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 sending while the app is running, use the method setLocationTracking(_ enabled: Bool) of the YMMYandexMetrica class.

YMMYandexMetrica.setTrackLocationEnabled(false)
Copied to clipboard

Setting device location manually

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

By default, the device location is detected by the library. To send your own device location information, pass an object of the class CLLocation into the method YMMYandexMetrica.setLocation(_ location: CLLocation?.

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

To send your custom event without nested parameters, pass to the method
YMMYandexMetrica.reportEvent(_ message: String, onFailure: ((NSError) -> Void)?)
Copied to clipboard
the following parameters:
  • message — Short name or description of the event;
  • onFailure — The block the error is passed to. If you do not want to track the error, pass nil for this block.
YMMYandexMetrica.reportEvent("Updates installed", onFailure: { (error) in
    print("DID FAIL REPORT EVENT: %@", message)
    print("REPORT ERROR: %@", error?.localizedDescription)
}
Copied to clipboard

Sending a custom event with nested parameters

To send your custom event without nested parameters, pass to the method
YMMYandexMetrica.reportEvent(_ message: String, parameters params: [NSObject : AnyObject]?, onFailure: ((NSError) -> Void)?)
Copied to clipboard
the following parameters:
  • message — Short name or description of the event;
  • params — Nested parameters as “key-value” pairs;
  • onFailure — The block the error is passed to. If you do not want to track the error, pass nil for this block.
let params : [String : 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

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

For more information about events, see Events.

Sending an error message

To send a custom error message, pass to the method

YMMYandexMetrica.reportError(_ message: String, exception: NSException?, onFailure: ((NSError) -> Void)?)
Copied to clipboard
the following parameters:
  • message — Short name or description of the event;
  • exceptionNSException type object to pass to the server. It can take the nil value.
  • onFailure — The block the error is passed to. If you do not want to track the error, pass nil for this block.
do {
    try self.doWork();
} catch let exception as NSException {
    YMMYandexMetrica.reportError("doWork failed", exception: exception, onFailure: nil)
}
Copied to clipboard

Sending profile attributes

To send profile attributes, pass to the method
YadnexMetrica.reportUserProfile(_ userProfile: YMMUserProfile, onFailure: ((NSError) -> Void)?)
the following parameters:
  • userProfile — An object that contains an array of attribute updates. To create profile attributes, use methods of the YMMProfileAttribute class.
  • onFailure — The block the error is passed to. If you do not want to track the error, pass nil for this block.
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.applyFromArray([
    // 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.reportUserProfile(profile, onFailure: { (error) in
    print("REPORT ERROR: %@", error.localizedDescription)
})
Copied to clipboard

Sending ProfileId

To send the ProfileId, use the setUserProfileID(_ userProfileID: String?) method of the YandexMetrica class.

If you don't configure ProfileId sending in the SDK, the web interface displays the appmetrica_device_id value.
YandexMetrica.setUserProfileID("id")
Copied to clipboard

Sending Revenue

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

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

Step 1. Test sending Revenue

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

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

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

  1. Initialize the YMMMutableRevenueInfo instance.
  2. To validate a purchase, specify transactionID and receiptData. You should receive them before invoking SKPaymentQueue.default ().finishTransaction(transaction).
  3. Send the YMMMutableRevenueInfo instance to the test API key using the YMMYandexMetricaReporting reporter. For more information about reporters, see Usage examples.
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

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("REPORT ERROR: \(error.localizedDescription)")
})
Copied to clipboard

Setting the length of the session timeout

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

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

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

where 1.13.2 is the app version.

Tracking app openings via deeplinks

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

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

To track app openings that use deeplinks and Universal Links, use the handleOpenURL(_:) method.

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

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, the user is counted as a new user when the app is opened for the first time. If you connect the AppMetrica SDK to an application that already has active users, you can set up tracking new users. To configure this, initialize the AppMetrica SDK using the extended configuration YMMYandexMetricaConfiguration:

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?.handleFirstActivationAsUpdateEnabled = !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 BOOL 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

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 YMMYandexMetrica.setStatisticsSending:(Bool)enabled method to enable it.

// Checking the status of the boolean variable. It shows the user confirmation.
if flag {
    // Enabling sending statistics.
    YMMYandexMetrica.setStatisticsSending(true);
}
Copied to clipboard