Connecting the AppMetrica Push SDK

Before using the AppMetrica Push SDK 0.7.1, you need to enable and initialize the AppMetrica SDK version 3.0.0 or higher (3.4.1 is recommended).

  1. Enabling and initalizing the library
  2. Sending additional information
  3. Defining the recipient of a notification

Enabling and initalizing the library

Step 1. Add the library to your project

The library has been adapted for use with the CocoaPods dependency manager. To enable the library, add a dependency to the project's Podfile:

 pod 'YandexMobileMetricaPush', '0.7.1'
If you don't use CocoaPods
  1. Download the AppMetrica Push library.
  2. Add YandexMobileMetricaPush.framework to the project.
Note. The AppMetrica SDK and AppMetrica Push SDK libraries must both be enabled in one of these ways.

Step 2. Register your app in the Apple Push Notification Service (APNs)

Registration prepares the app to work with push notifications. To send notifications to devices with iOS version 7 and higher, make the following changes to the application code:

// Register for push notifications
if #available(iOS 8.0, *) {
    if #available(iOS 10.0, *) {
        // iOS 10.0 and above.
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
            // Enable or disable features based on authorization.
        }
    } else {
        // iOS 8 and iOS 9.
        let settings = UIUserNotificationSettings(types: [.badge, .alert, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }
    application.registerForRemoteNotifications()
} else {
    // iOS 7
    application.registerForRemoteNotifications(matching: [.badge, .alert, .sound])
}
This data is usually passed in the following method
func application(_ application: UIApplication, didFinishLaunchingWithOptions
                 launchOptions: [UIApplicationLaunchOptionsKey :Any]? = nil) -> Bool

To integrate the SDK with iOS 10 and higher, add the following code:

import UserNotifications
// In the method "func application(_ application: UIApplication, didFinishLaunchingWithOptions 
//                            launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool":
if #available(iOS 10.0, *) {
    let delegate = YMPYandexMetricaPush.userNotificationCenterDelegate()
    UNUserNotificationCenter.current().delegate = delegate
}

If you have already set another delegate, just set the delegate as a middleware before your own delegate:

YMPYandexMetricaPush.userNotificationCenterDelegate().nextDelegate = yourDelegate

For more details about the methods used, see the documentation at developer.apple.com:

Step 3. Register a device token for your app

To send push notifications using AppMetrica, your app's device token is required. To register it, add the folowing code to AppDelegate:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    // If the AppMetrica SDK library was not initialized before this step,
    // calling the method causes the app to crash.
    YMPYandexMetricaPush.setDeviceTokenFrom(deviceToken)
}

To register the device token and send the APN environments, add the following code:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    // If the AppMetrica SDK library wasn't initialized prior to this step,
    // calling this method will cause the app to crash.
    #if DEBUG
        let pushEnvironment = YMPYandexMetricaPushEnvironment.development
    #else
        let pushEnvironment = YMPYandexMetricaPushEnvironment.production
    #endif
    YMPYandexMetricaPush.setDeviceTokenFrom(deviceToken, pushEnvironment: pushEnvironment)
}
Attention. AppMetrica allows you to send push notifications to Sandbox APNs. However, push notification processing may not work correctly if versions of the application with different environments were run on the device(development and production). To avoid this issue, you can use a separate test API key for development environment.

Step 4. Configure handling the opening of push notifications.

Add the following code to the corresponding methods AppDelegate:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any])
{
    self.handlePushNotification(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
{
    self.handlePushNotification(userInfo)
    completionHandler(.newData)
}

func handlePushNotification(_ userInfo: [AnyHashable : Any])
{
    // Track received remote notification.
    // Method [YMMYandexMetrica activateWithApiKey:] should be called before using this method.
    YMPYandexMetricaPush.handleRemoteNotification(userInfo)
}

Step 5. (Optional) Enable push tokens update

The APNS service can withdraw the push token of the device, for example, if the user did not launch the application for a long time. AppMetrica stores push tokens on the server and can not send a push message to a device with an obsolete token.

To automatically collect current push token go to the application settings in the AppMetrica interface and enable the Update tokens with a Silent Push notification option in the Push Notifications tab.

Sending additional information

You can send additional information with the push notification if necessary. This data is specified in the AppMetrica web interface when configuring the push campaign. To get this information, use the following method:

let userData = YMPYandexMetricaPush.userData(forNotification: userInfo)

where userInfo contains information about the push notification.

Defining the recipient of a notification

AppMetrica allows you to detect "own" push notifications, if several Push SDKs were built into the application.

To detect, if the AppMetrica is the recipient of a notification, use the following method:

let isRelatedToAppMetricaSDK = YMPYandexMetricaPush.isNotificationRelated(toSDK: userInfo)