Installation and initialization
- 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
- Step 7. (Optional) Set up push notification statistics collection
- Sending additional information
- Defining the recipient of a notification
Before using the AppMetrica Push SDK 2.2.1, you need to enable and initialize the AppMetrica SDK version 5.0.0 or higher.
Step 1. Enable the library
The library can work with the following dependency managers:
To connect the Push SDK library, add the following dependencies to your project's Podfile:
pod 'AppMetricaPush', '~> 2.2.1' # Main module for working with Push SDK, it's required for connecting
pod 'AppMetricaPushLazy', '~> 2.2.1' # Additional module for lazy push notifications
Integration via the Xcode interface
To connect the library, follow these steps:
-
In the Xcode project navigator (Project Navigator) window, select your project (if Workspace is used). In the top menu, click File and select Add Package Dependencies....
-
Specify the repository URL
https://github.com/appmetrica/push-sdk-ios
. -
Leave only the required modules (to disable a module, select
None
inAdd to Target
):AppMetricaPush
: The main mandatory Push SDK module. You need to enable it to use AppMetrica.AppMetricaPushLazy
: Additional module for lazy push notifications.
Integration via the Package.swift manifest
First, add the following dependency to the dependencies:
array of your package:
dependencies: [
.package(
url: "https://github.com/appmetrica/push-sdk-ios",
from: "2.2.1"
)
],
The AppMetrica Push SDK modules that you can enable depending on the needs of your project:
AppMetricaPush
: The main mandatory Push SDK module. You need to enable it to use AppMetrica.AppMetricaPushLazy
: Additional module for lazy push notifications.
Example of connecting modules in the dependencies:
array of the target:
.target(
name: "MyTargetName",
dependencies: [
.product(name: "AppMetricaPush", package: "push-sdk-ios"),
// .product(name: "AppMetricaPushLazy", package: "push-sdk-ios"), // This module is disabled
]
),
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 iOS devices, make the following changes to the app's code:
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:\[.badge, .alert, .sound\]) { (granted, error) in
// Enable or disable features based on authorization.
}
application.registerForRemoteNotifications()
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
:
UNAuthorizationOptions options =
UNAuthorizationOptionAlert |
UNAuthorizationOptionBadge |
UNAuthorizationOptionSound;
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:options completionHandler:^(BOOL granted, NSError *error) {
// Enable or disable features based on authorization.
}];
[application registerForRemoteNotifications];
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.
AppMetricaPush.setDeviceTokenFrom(deviceToken)
}
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.
[AMPAppMetricaPush setDeviceTokenFromData: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 was not initialized before this step,
// calling the method causes the app to crash.
#if DEBUG
let pushEnvironment = AppMetricaPushEnvironment.development
#else
let pushEnvironment = AppMetricaPushEnvironment.production
#endif
AppMetricaPush.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
AMPAppMetricaPushEnvironment pushEnvironment = AMPAppMetricaPushEnvironmentDevelopment;
#else
AMPAppMetricaPushEnvironment pushEnvironment = AMPAppMetricaPushEnvironmentProduction;
#endif
[AMPAppMetricaPush setDeviceTokenFromData:deviceToken pushEnvironment:pushEnvironment];
}
Alert
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
Configure handling the opening of push notifications:
-
Use the delegate
UserNotificationCenterDelegate
/AMPUserNotificationCenterDelegate
. It handles the receipt of push notifications automatically when they're opened.Make the following changes to the code:
SwiftObjective-Cimport UserNotifications // In the "func application(_ application: UIApplication, didFinishLaunchingWithOptions // launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool" method: let delegate = AppMetricaPush.userNotificationCenterDelegate UNUserNotificationCenter.current().delegate = delegate
#import <UserNotifications/UserNotifications.h> // In the "- (BOOL)application:(UIApplication *)application // didFinishLaunchingWithOptions:(NSDictionary *)launchOptions" method: [UNUserNotificationCenter currentNotificationCenter].delegate = [AppMetricaPush userNotificationCenterDelegate];
To track push notification openings and other actions with them, create your own delegate named
UNUserNotificationCenterDelegate
and add it tonextDelegate
:SwiftObjective-CAppMetricaPush.userNotificationCenterDelegate.nextDelegate = yourDelegate
[AMPAppMetricaPush userNotificationCenterDelegate].nextDelegate = yourDelegate;
After that, you can use the appropriate methods of your delegate.
-
If you also use UISceneDelegate, add the following code to the
scene(_:willConnectTo:options:)
method:SwiftObjective-Cfunc scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { AppMetricaPush.handleSceneWillConnectToSession(with: connectionOptions) }
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions { [AMPAppMetricaPush handleSceneWillConnectToSessionWithOptions:connectionOptions]; }
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
Note
The functionality is not available in the web interface of push campaigns.
You can configure uploading attached files in push notifications:
- 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.
Step 7. (Optional) Set up push notification statistics collection
To collect information about push notification delivery, set up statistics collection by following the instructions.
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 = AppMetricaPush.userData(forNotification: userInfo)
NSString *userData = [AMPAppMetricaPush userDataForNotification: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 = AppMetricaPush.isNotificationRelated(toSDK: userInfo)
BOOL isRelatedToAppMetricaSDK = [AMPAppMetricaPush isNotificationRelatedToSDK:userInfo];
See also
If you didn't find the answer you were looking for, you can use the feedback form to submit your question. Please describe the problem in as much detail as possible. Attach a screenshot if possible.