Подключение и инициализация AppMetrica Push SDK
Перед началом работы с AppMetrica Push SDK версии 1.3.0 необходимо подключить и инициализировать AppMetrica SDK не ниже версии 3.4.1.
- Шаг 1. Подключите библиотеку
- Шаг 2. Зарегистрируйте приложение в Apple Push Notification Service (APNs)
- Шаг 3. Зарегистрируйте device token вашего приложения
- Шаг 4. Настройте обработку открытия push-уведомления
- Шаг 5. (Опционально) Включите актуализацию push-токенов
- Шаг 6. (Опционально) Настройте загрузку прикрепленных файлов
- Отправка дополнительной информации
- Определение получателя уведомления
Шаг 1. Подключите библиотеку
Библиотека может работать со следующими системами управления зависимостями:
Библиотека поддерживает статический и динамический фреймворки для CocoaPods. Для подключения библиотеки добавьте в Podfile проекта зависимость:
Статический фреймворк
pod 'YandexMobileMetricaPush', '1.3.0'
СкопированоДинамический фреймворк
pod 'YandexMobileMetricaPush/Dynamic', '1.3.0'
Скопировано
Для подключения библиотеки добавьте в Cartfile
следующую зависимость и сохраните файл:
binary "https://raw.githubusercontent.com/yandexmobile/metrica-push-sdk-ios/master/YandexMobileMetricaPush.json" ~> 1.3.0
Скопировано
Чтобы подключить библиотеку, выполните следующее:
В Xcode, в своем проекте выберите вкладку Swift Packages.
Укажите URL репозитория
https://github.com/yandexmobile/metrica-push-sdk-ios
, в нем находится Swift-пакет.Настройте правило для выбора версии пакета.
Ограничение.Подключение с помощью Swift Package Manager поддерживается, начиная с версии 1.0.0 AppMetrica Push SDK.
- Выберите необходимые библиотеки.
- Добавьте
YandexMobileMetricaPush.framework
в проект.
Для подключения библиотеки выполните следующее:
Шаг 2. Зарегистрируйте приложение в Apple Push Notification Service (APNs)
Регистрация необходима для подготовки приложения к работе с push-уведомлениями. Для отправки уведомлений на устройства с iOS версии 7 и выше добавьте следующие изменения в код приложения:
// 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()
Скопировано
Как правило, эти данные передаются в следующем методе:
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey :Any]? = nil) -> Bool
Подробно об используемых методах в документации на 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]; }
Скопировано
Как правило, эти данные передаются в следующем методе:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
Подробно об используемых методах в документации на developer.apple.com:
Шаг 3. Зарегистрируйте device token вашего приложения
Для отправки push-уведомления с помощью AppMetrica необходим device token вашего приложения. Чтобы зарегистрировать его:
Добавьте следующий код в 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) }
Скопировано
Добавьте следующий код в вашу реализацию 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]; }
Скопировано
Чтобы зарегистрировать device token и отправить окружение APNs, используйте следующий код:
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) }
Скопировано
- (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]; }
Скопировано
Шаг 4. Настройте обработку открытия push-уведомления
Настройте обработку открытия push-уведомления:
Добавьте следующий код в соответствующие методы
AppDelegate
|UIApplicationDelegate
: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) }
Скопировано- (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]; }
СкопированоЕсли вы дополнительно используете UISceneDelegate, добавьте следующий код в метод
scene(_:willConnectTo:options:)
:func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { YMPYandexMetricaPush.handleSceneWillConnectToSession(with: connectionOptions) }
Скопировано- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions { [YMPYandexMetricaPush handleSceneWillConnectToSessionWithOptions:connectionOptions]; }
Скопировано
- Обработка push-уведомлений iOS 9 и ниже
-
Если у вас iOS 9 и ниже, или вы не используете новую функциональность уведомлений iOS 10, то отслеживать получение push-уведомлений нужно будет самостоятельно. Чтобы отслеживать открытие и другие действия с push-уведомлениями, воспользуйтесь соответствующими методами
UIApplicationDelegate
. - Обработка push-уведомлений iOS 10 и выше
-
Если у вас iOS 10 и выше, и вы хотите использовать новый представленный с iOS 10 тип push-уведомлений, то воспользуйтесь делегатом
YMPUserNotificationCenterDelegate
. Он обрабатывает получение push-уведомлений автоматически, при их открытии.Внесите следующие изменения в код:
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 }
Скопировано#import <UserNotifications/UserNotifications.h> // In the "- (BOOL)application:(UIApplication *)application // didFinishLaunchingWithOptions:(NSDictionary *)launchOptions" method: if ([UNUserNotificationCenter class] != Nil) { [UNUserNotificationCenter currentNotificationCenter].delegate = [YMPYandexMetricaPush userNotificationCenterDelegate]; }
СкопированоЧтобы отслеживать открытие и другие действия с push-уведомлениями, создайте собственный делегат
UNUserNotificationCenterDelegate
и добавьте его вnextDelegate
:YMPYandexMetricaPush.userNotificationCenterDelegate().nextDelegate = yourDelegate
Скопировано[YMPYandexMetricaPush userNotificationCenterDelegate].nextDelegate = yourDelegate;
СкопированоПосле этого можно использовать соответствующие методы своего делегата.
Шаг 5. (Опционально) Включите актуализацию push-токенов
Сервис APNS может отозвать push-токен устройства, например, если пользователь долго не запускал приложение. AppMetrica хранит push-токены на сервере и не может отправить push-уведомление на устройство с устаревшим токеном.
Чтобы автоматически собирать актуальные push-токены, перейдите в настройки приложения в веб-интерфейса AppMetrica и выберите опцию Актуализировать токены с помощью Silent Push-уведомлений во вкладке Push-уведомления.
Шаг 6. (Опционально) Настройте загрузку прикрепленных файлов
В веб-интерфейсе push-кампаний функциональность недоступна.
- Настройте загрузку прикрепленных файлов с помощью метода downloadAttachmentsForNotificationRequest Push SDK. С примером интеграции можно ознакомиться в статье Загрузка прикрепленных файлов.
- Прикрепите вложения (параметр
attachments
) с помощью операции Отправка push-сообщений Push API.
Отправка дополнительной информации
При необходимости вы можете передавать вместе с push-уведомлением дополнительную информацию. Эти данные указываются в веб-интерфейсе AppMetrica при настройке push-кампании. Чтобы получать эту информацию, используйте метод:
let userData = YMPYandexMetricaPush.userData(forNotification: userInfo)
Скопировано
NSString *userData = [YMPYandexMetricaPush userDataForNotification:userInfo];
Скопировано
где userInfo
содержит данные о push-уведомлении.
Определение получателя уведомления
AppMetrica позволяет определить «свои» push-уведомления, если в приложение были встроены несколько Push SDK.
Чтобы определить, является ли AppMetrica получателем сообщения, используйте следующий метод:
let isRelatedToAppMetricaSDK = YMPYandexMetricaPush.isNotificationRelated(toSDK: userInfo)
Скопировано
BOOL isRelatedToAppMetricaSDK = [YMPYandexMetricaPush isNotificationRelatedToSDK:userInfo];
Скопировано