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)
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.activateWithConfiguration(configuration!)
    return true
}

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!)
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 reporting = YMMYandexMetrica.reporterForApiKey("API_key")
reporting.reportEvent("Updates installed") { (error) in
    print("DID FAIL REPORT EVENT: %@", message)
    print("REPORT ERROR: %@", error?.localizedDescription)
}

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

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

Monitoring app crashes

Reports on app crashes are sent by default.

To disable automatic monitoring, initialize the library with the configuration in which sending crashes is disabled. To do this, set the 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.activateWithConfiguration(configuration!)

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.activateWithConfiguration(configuration!)

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

YMMYandexMetrica.setTrackLocationEnabled(false)

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)
}

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)?)
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)
}

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)?)
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 = ["key1": "value1", "key2": "value2"]
YMMYandexMetrica.reportEvent("EVENT", parameters: params, onFailure: { (error) in
    print("DID FAIL REPORT EVENT: %@", message)
    print("REPORT ERROR: %@", error?.localizedDescription)
}

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

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

Sending an error message

To send a custom error message, pass to the method

YMMYandexMetrica.reportError(_ message: String, exception: NSException?, onFailure: ((NSError) -> Void)?)
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)
}

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)
})

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.activateWithConfiguration(configuration!)

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.activateWithConfiguration(configuration!)

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
}

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.activateWithConfiguration(configuration!)

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.activateWithConfiguration(configuration!)

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