Connecting the AppMetrica Push SDK
Before using the AppMetrica Push SDK 1.3.0, you need to enable and initialize the AppMetrica SDK version 3.4.1 or higher.
- Step 1. Enable the library
- Step 2. Register your app in the Apple Push Notification Service (APNs)
- Step 3. Register a device token for your app
- Step 4. Configure handling the opening of push notifications.
- Step 5. (Optional) Enable push tokens update
- Step 6. (Optional) Configure uploading attached files
- Sending additional information
- Defining the recipient of a notification
Step 1. Enable the library
The library can work with the following dependency managers:
The library supports static and dynamic frameworks for CocoaPods. To enable the library, add a dependency to the project's Podfile:
Static framework
pod 'YandexMobileMetricaPush', '1.3.0'
Copied to clipboardDynamic framework
pod 'YandexMobileMetricaPush/Dynamic', '1.3.0'
Copied to clipboard
To enable the library, add the following dependency to the Cartfile
and save the file:
binary "https://raw.githubusercontent.com/yandexmobile/metrica-push-sdk-ios/master/YandexMobileMetricaPush.json" ~> 1.3.0
Copied to clipboard
To connect the library, follow these steps:
In Xcode, go to the Swift Packages tab for your project.
Specify the repository URL
https://github.com/yandexmobile/metrica-push-sdk-ios
, which contains a Swift package.Configure a rule for selecting the package version.
Restriction.Connection using Swift Package Manager is supported starting from version 1.0.0 of the AppMetrica SDK.
- Select the required libraries.
- Add
YandexMobileMetricaPush.framework
to the project.
To enable the library, follow these steps:
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 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()
Copied to clipboard
This data is usually passed in the following method:
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey :Any]? = nil) -> Bool
For more details about the methods used, see the documentation at developer.apple.com:
if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) { if (NSClassFromString(@"UNUserNotificationCenter") != Nil) { // iOS 10.0 and above UNAuthorizationOptions options = UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound; UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; [center requestAuthorizationWithOptions:options completionHandler:^(BOOL granted, NSError *error) { // Enable or disable features based on authorization. }]; } else { // iOS 8 and iOS 9 UIUserNotificationType userNotificationTypes = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound; UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:userNotificationTypes categories:nil]; [application registerUserNotificationSettings:settings]; } [application registerForRemoteNotifications]; }
Copied to clipboard
This data is usually passed in the following method:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
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 following 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) }
Copied to clipboard
Add the following code to your implementation of UIApplicationDelegate
:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { // If the AppMetrica SDK library was not initialized before this step, // calling the method causes the app to crash. [YMPYandexMetricaPush setDeviceTokenFromData:deviceToken]; }
Copied to clipboard
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 was not initialized before this step, // calling the method causes the app to crash. #if DEBUG let pushEnvironment = YMPYandexMetricaPushEnvironment.development #else let pushEnvironment = YMPYandexMetricaPushEnvironment.production #endif YMPYandexMetricaPush.setDeviceTokenFrom(deviceToken, pushEnvironment: pushEnvironment) }
Copied to clipboard
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { // If the AppMetrica SDK library was not initialized before this step, // calling the method causes the app to crash. #ifdef DEBUG YMPYandexMetricaPushEnvironment pushEnvironment = YMPYandexMetricaPushEnvironmentDevelopment; #else YMPYandexMetricaPushEnvironment pushEnvironment = YMPYandexMetricaPushEnvironmentProduction; #endif [YMPYandexMetricaPush setDeviceTokenFromData:deviceToken pushEnvironment:pushEnvironment]; }
Copied to clipboard
Step 4. Configure handling the opening of push notifications.
Configure handling the opening of push notifications:
Add the following code to the appropriate
AppDelegate
|UIApplicationDelegate
methods: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) }
Copied to clipboard- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [YMPYandexMetricaPush handleApplicationDidFinishLaunchingWithOptions:launchOptions]; return YES; } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { [YMPYandexMetricaPush handleRemoteNotification:userInfo]; } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { [YMPYandexMetricaPush handleRemoteNotification:userInfo]; }
Copied to clipboardIf you also use UISceneDelegate, add the following code to the
scene(_:willConnectTo:options:)
method:func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { YMPYandexMetricaPush.handleSceneWillConnectToSession(with: connectionOptions) }
Copied to clipboard- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions { [YMPYandexMetricaPush handleSceneWillConnectToSessionWithOptions:connectionOptions]; }
Copied to clipboard
- Handling push notifications for iOS 9 and below
-
If you have iOS 9 and lower or you don't use the new notification feature on iOS 10, you'll need to track the receipt of push notifications yourself. To track push notification openings and other actions with them, use the appropriate
UIApplicationDelegate
methods. - Handling push notifications for iOS 10 and higher
-
If you have iOS 10 or higher and want to use the new type of push notifications introduced in iOS 10, use the
YMPUserNotificationCenterDelegate
delegate. It handles the receipt of push notifications automatically when they're opened.Make the following changes to the code:
import UserNotifications // In the "func application(_ application: UIApplication, didFinishLaunchingWithOptions // launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool" method: if #available(iOS 10.0, *) { let delegate = YMPYandexMetricaPush.userNotificationCenterDelegate() UNUserNotificationCenter.current().delegate = delegate }
Copied to clipboard#import <UserNotifications/UserNotifications.h> // In the "- (BOOL)application:(UIApplication *)application // didFinishLaunchingWithOptions:(NSDictionary *)launchOptions" method: if ([UNUserNotificationCenter class] != Nil) { [UNUserNotificationCenter currentNotificationCenter].delegate = [YMPYandexMetricaPush userNotificationCenterDelegate]; }
Copied to clipboardTo track push notification openings and other actions with them, create your own delegate named
UNUserNotificationCenterDelegate
and add it tonextDelegate
:YMPYandexMetricaPush.userNotificationCenterDelegate().nextDelegate = yourDelegate
Copied to clipboard[YMPYandexMetricaPush userNotificationCenterDelegate].nextDelegate = yourDelegate;
Copied to clipboardAfter that, you can use the appropriate methods of your delegate.
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 notification 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.
Step 6. (Optional) Configure uploading attached files
The functionality is not available in the web interface of push campaigns.
- Configure uploading attached files in push notifications by calling the downloadAttachmentsForNotificationRequest method in the Push SDK. See an example of integration in the article Uploading attached files.
- Add attachments (the
attachments
parameter) using the Sending push messages operation in the Push API.
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)
Copied to clipboard
NSString *userData = [YMPYandexMetricaPush userDataForNotification:userInfo];
Copied to clipboard
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)
Copied to clipboard
BOOL isRelatedToAppMetricaSDK = [YMPYandexMetricaPush isNotificationRelatedToSDK:userInfo];
Copied to clipboard