AppMetrica Push SDK — это набор библиотек для работы с push-уведомлениями. Подключив AppMetrica Push SDK, вы можете создать и настроить кампанию push-уведомлений, а затем отслеживать статистику в веб-интерфейсе AppMetrica.
- получение и отображение Push уведомлений
- получение Silent Push уведомлений
- обработка payload из уведомлений
- отображение изображения в уведомлениях
- поддержка действия deeplink, при открытии уведомления
- поддержка действия URL, при открытии уведомления
Добавьте это в файл pubspec.yaml вашего проекта:
dependencies:
firebase_core: <lastles>
firebase_analytics: <lastles>
appmetrica_plugin: <lastles>
appmetrica_push_ios: <lastles>
- создать проект в AppMetrica
- создать проект в Firebase, добавить iOS приложение и загрузить конфигурационный файл
GoogleService-Info.plist
- в настройках проекта AppMetrica получить
API key (для использования в SDK)
- настроить AppMetrica для работы с APNs
(Опционально) Включите актуализацию push-токенов: Сервис APNs может отозвать push-токен устройства, например, если пользователь долго не запускал приложение. AppMetrica хранит push-токены на сервере и не может отправить push-уведомление на устройство с устаревшим токеном. Чтобы автоматически собирать актуальные push-токены, перейдите в настройки приложения в веб-интерфейса AppMetrica и выберите опцию Актуализировать токены с помощью Silent Push-уведомлений во вкладке Push-уведомления.
Разместите конфигурационный файл GoogleService-Info.plist
в <project>/ios/Runner/
через XCode.
- В Xcode выберите
File → New → Target
. - В разделе расширений iOS выберите из списка
Notification Service Extension
и нажмитеNext
. - Введите название расширения в поле
Product Name
и нажмитеFinish
.
- В настройках проекта Xcode перейдите во вкладку Capabilities.
- Включите App Groups для созданного расширения и для приложения. Чтобы переключиться между расширением и приложением, нажмите на панели настроек проекта кнопку или на выпадающий элемент.
- В разделе App Groups создайте группу с помощью кнопки +. Название группы понадобится при дальнейшей настройке.
- Выберите созданную группу для приложения и для созданного расширения.
В созданом Notification Service Extension
измените код следующим образом:
import UserNotifications
import YandexMobileMetricaPush
class <YourNotificationServiceName>: UNNotificationServiceExtension {
private var contentHandler: ((UNNotificationContent) -> Void)?
private var bestAttemptContent: UNMutableNotificationContent?
private let syncQueue = DispatchQueue(label: "<YourNotificationServiceName>.syncQueue")
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if bestAttemptContent != nil {
// Modify the notification content here...
YMPYandexMetricaPush.setExtensionAppGroup("<your.app.group.name>")
YMPYandexMetricaPush.handleDidReceive(request)
}
YMPYandexMetricaPush.downloadAttachments(for: request) { [weak self] attachments, error in
if let error = error {
print("Error: \(error)")
}
self?.completeWithBestAttempt(attachments: attachments)
}
}
override func serviceExtensionTimeWillExpire() {
completeWithBestAttempt(attachments: nil)
}
func completeWithBestAttempt(attachments: [UNNotificationAttachment]?) {
syncQueue.sync { [weak self] in
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
if let attachments = attachments {
bestAttemptContent.attachments = attachments
}
contentHandler(bestAttemptContent)
self?.bestAttemptContent = nil
self?.contentHandler = nil
}
}
}
}
В файле <project>/ios/Runner/AppDelegate.swift
добавить следующие строки в application:didFinishLaunchingWithOptions
между GeneratedPluginRegistrant.register
и return super.application
:
...
YMPYandexMetricaPush.setExtensionAppGroup("<your.app.group.name>")
...
В файле <project>/ios/Podfile
изменить и добавить:
platform :ios, '10.0'
...
target '<YourNotificationServiceName>' do
use_frameworks!
pod 'YandexMobileMetricaPush'
end
post_install do |installer|
installer.pods_project.targets.each do |target|
# In case of `Multiple commands produce .../XCFrameworkIntermediates/YandexMobileMetrica` problem
if target.name == 'YandexMobileMetrica-Static_Core'
target.remove_from_project
end
flutter_additional_ios_build_settings(target)
end
end
await Firebase.initializeApp();
await FirebaseAnalytics.instance.setAnalyticsCollectionEnabled(true);
// AppMetrica.activate должна быть вызвана до AppmetricaPush.activate
await AppMetrica.activate(AppMetricaConfig('<AppMetrica API key>'));
await AppmetricaPushIos.instance.activate();
await AppmetricaPushIos.instance.requestPermission(PermissionOptions(
alert: true,
badge: true,
sound: true,
));
// Получить токен PUSH сервиса
await AppmetricaPushIos.instance.getTokens();
// Стрим токенов PUSH сервиса. Приходит, когда токен на устройстве меняется
// Обратите внимание что это stream broadcast
AppmetricaPushIos.instance.tokenStream.listen((Map<String, String?> data) => print('token: $data'));
// Стрим silent push, в качестве данных приходит payload
// Обратите внимание что это stream broadcast
AppmetricaPushIos.instance.onMessage
.listen((String data) => print('onMessage: $data'));
// Стрим push, в качестве данных приходит payload
// Обратите внимание что это stream broadcast
AppmetricaPushIos.instance.onMessageOpenedApp
.listen((String data) => print('onMessageOpenedApp: $data'));
Пример работы SDK доступен в Example