---
metadata:
  - name: generator
    content: Diplodoc Platform v5.64.0
alternate:
  - https://boost.yandex.com/doc/en/analytics/content/sdk/ios/push/quick-start.md
  - https://boost.yandex.com/doc/ru/analytics/content/sdk/ios/push/quick-start.md
  - https://boost.yandex.com/doc/zh/analytics/content/sdk/ios/push/quick-start.md
  - href: https://boost.yandex.com/doc/zh/analytics/content/sdk/ios/push/quick-start.md
    type: text/markdown
    title: Markdown version
  - href: https://boost.yandex.com/doc/zh/llms.txt?revision=r21738064
    rel: describedby
---
> **Documentation Index:** Fetch the complete configuration index at https://boost.yandex.com/doc/zh/llms.txt?revision=r21738064

# 安装和初始化

在使用 AppMetrica Push SDK 3.4.0 之前，需要 [启用并初始化 AppMetrica SDK](https://boost.yandex.com/doc/zh/analytics/content/sdk/ios/analytics/quick-start.md) 版本 5.9.0 或更高。

## 步骤 1. 启用库 {#installation}

该库可以与以下依赖管理器兼容：

{% list tabs %}

- CocoaPods

   要连接 Push SDK 库，请在项目的 Podfile 中添加以下依赖：

   ```ruby translate=no
   pod 'AppMetricaPush', '~> 3.4.0' # Main module for working with Push SDK, it's required for connecting
   pod 'AppMetricaPushLazy', '~> 3.4.0' # Additional module for lazy push notifications
   ```

- SPM 在 Xcode

   **通过 Xcode 界面进行集成**

   要连接库，请执行以下步骤：

   1. 在 Xcode 项目导航器 (**项目导航器**) 窗口中，选择您的项目（如果使用 **工作区**）。 在顶部菜单中，点击**文件**，然后选择**添加包依赖...**。

      ![项目导航器](../../../../_images/xcode_add_package_dependency.png)

   2. 指定仓库 URL `https://github.com/appmetrica/push-sdk-ios`

      ![仓库 URL](../../../../_images/spm-url-push.png)

   3. 只保留需要的模块（要禁用模块，请在“添加到目标”中选择`无`）：``

      ![必需模块](../../../../_images/spm-select-packages-push.png)

      * `AppMetricaPush`：主要的必需推送 SDK 模块。 你需要启用它才能使用 AppMetrica。
      * `AppMetricaPushLazy`：额外模块，用于延迟推送通知。

- Package.swift

   **通过 Package.swift 清单进行集成**

   首先，将以下依赖项添加到你的包的 `dependencies:` 数组中：

   ```swift translate=no
   dependencies: [
      .package(
         url: "https://github.com/appmetrica/push-sdk-ios",
         from: "3.4.0"
      )
   ],
   ```

   根据项目需求可以启用的AppMetrica Push SDK 模块：

   * `AppMetricaPush`：主要的必需的Push SDK模块。 你需要启用它才能使用 AppMetrica。
   * `AppMetricaPushLazy`：额外模块，用于延迟推送通知。

   示例：在目标的 `dependencies` 数组中连接模块

   ```swift translate=no
   .target(
      name: "MyTargetName",
      dependencies: [
         .product(name: "AppMetricaPush", package: "push-sdk-ios"),
         // .product(name: "AppMetricaPushLazy", package: "push-sdk-ios"), // This module is disabled
      ]
   ),
   ```

{% endlist %}

## 步骤 2. 配置AppMetrica推送 {#setup}

在应用程序和扩展中设置AppMetrica，如[在 App 扩展中工作](https://boost.yandex.com/doc/zh/analytics/content/sdk/ios/analytics/ios-appgroup.md)中所述。
AppMetrica-6.2.0 和 AppMetricaPush-3.4 将其配置共享到 AppGroup。

{% list tabs group=instructions %}

- 面向对象的 C

   将以下代码添加到 `UIApplicationDelegate` 方法的相应实现中：

   ```objectivec translate=no
   - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
   {
       // Activating AppMetrica.
       AMAAppMetricaConfiguration *configuration = [[AMAAppMetricaConfiguration alloc] initWithAPIKey:@"YOUR-API-KEY"];
       [AMAAppMetrica activateWithConfiguration:configuration];
       ...
       [AMPAppMetricaPush setExtensionAppGroup:appGroup]; // optional, need to send stored events from AppMetricaPush-2.2 and earlier
       ...
       [AMPAppMetricaPush handleApplicationDidFinishLaunchingWithOptions:launchOptions];
       ...
   }
   ```

- Swift

   将以下代码添加到 `AppDelegate` 方法的相应实现中：

   ```objectivec translate=no
   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey :Any]? = nil) -> Bool
   {
       // Activating AppMetrica.
       let configuration = AppMetricaConfiguration(apiKey: "YOUR-API-KEY")!
       AppMetrica.activate(with: configuration)
       ...
       AppMetricaPush.setExtensionAppGroup(appGroup) // optional, need to send stored events from AppMetricaPush-2.2 and earlier
       ...
       AppMetricaPush.handleApplicationDidFinishLaunching(options: launchOptions)
       ...
   }
   ```

{% endlist %}

### 收集关闭推送通知的交互数据 {#dismiss}

要收集推送通知关闭交互的统计数据，请为 ` UNNotificationCategory` 类设置以下选项：

{% list tabs group=instructions %}

- Objective-C

   ```objectivec translate=no
   options:UNNotificationCategoryOptionCustomDismissAction
   ```

- Swift

   ```swift translate=no
   options: UNNotificationCategory.customDismissAction
   ```

{% endlist %}

## 步骤 3. (_可选_) 在通知服务扩展中设置 AppMetrica {#notification}

通过 XCode 添加通知服务扩展
1. 在 Xcode 中，选择 **文件** → **新建** → **目标**。
2. 在**iOS**扩展部分，从列表中选择**Notification Service Extension**，然后点击**Next**。
3. 在**产品名称**字段中输入扩展名，然后点击**完成**。

在应用程序和扩展中设置AppMetrica，如[在 App 扩展中工作](https://boost.yandex.com/doc/zh/analytics/content/sdk/ios/analytics/ios-appgroup.md)所述。

1. 在 [developer.apple.com](https://developer.apple.com/account/resources/identifiers/list/bundleId) 为 Notification Service Extension 创建 Bundle ID。

2. 在 [developer.apple.com](https://developer.apple.com/account/resources/identifiers/list/applicationGroup) 中创建一个 AppGroup。

3. 将AppGroup添加到[配置文件](https://developer.apple.com/account/resources/profiles/list)中，用于应用程序和通知服务扩展。 确保 AppGroup 仅对您的应用及其扩展可用。 如果AppGroup被多个应用共享，AppMetrica可能会错误地统计安装量。

4. 打开 Xcode，并将 AppGroup 和 Keychain Access Group 添加到你的应用目标。

   ![到应用目标](../../../../_images/xcode-push-app.png){style="border: solid 1px #cccccc; max-width: 800px;"}

5. 打开 Xcode，并将 AppGroup 和 Keychain Access Group 添加到你的 NSE 目标中。

   ![到 NSE 目标](../../../../_images/xcode-push-nse.png){style="border: solid 1px #cccccc; max-width: 800px;"}

6. 将AppGroup添加到`Info.plist`。

   ![到 Info.plist](../../../../_images/xcode-push-infoplist.png){style="border: solid 1px #cccccc; max-width: 800px;"}

7. 检查权限，确保已添加 AppGroup 和 Keychain Access Group。

   ![检查权限](../../../../_images/xcode-push-entitlements.png){style="border: solid 1px #cccccc; max-width: 800px;"}

8. Implement the `通知服务`.


`AppMetricaPush`在通知服务扩展中从您的应用程序获取配置并自动激活AppMetrica.
要使用它，请在扩展类中添加以下代码：

{% list tabs group=instructions %}

- Swift

  ```swift translate=no
  class NotificationService: UNNotificationServiceExtension {

      var contentHandler: ((UNNotificationContent) -> Void)?
      var bestAttemptContent: UNMutableNotificationContent?

      override func didReceive(_ request: UNNotificationRequest,
                              withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
         AppMetricaPush.setExtensionAppGroup(appGroup) // optional, need to send stored events from AppMetricaPush-2.2 and earlier

         AppMetricaPush.handleDidReceive(request)

         self.contentHandler = contentHandler
         bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

         // custom logic

         AppMetrica.sendEventsBuffer()
      }

      override func serviceExtensionTimeWillExpire() {
         bestAttemptContent?()
      }
  }
  ```

- Objective-C

  ```objectivec translate=no
  @interface NotificationService: UNNotificationServiceExtension

  @property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
  @property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

  @end
  @implementation NotificationService

  + (void)initialize {
      if ([self class] == [NotificationService class]) {
          [AMPAppMetricaPush setExtensionAppGroup:appGroup]; // push saved events
      }
  }

  - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request
                    withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {

      [AMPAppMetricaPush handleDidReceiveNotificationRequest:request];

      self.contentHandler = contentHandler;
      self.bestAttemptContent = [request.content mutableCopy];

      // custom logic

      [AMAAppMetrica sendEventsBuffer]; // force send all events
  }

  - (void)serviceExtensionTimeWillExpire {
    if (self.bestAttemptContent != nil) {
      self.bestAttemptContent();
    }

  }

  @end
  ```

{% endlist %}

在扩展程序中可以使用AppMetrica的自定义配置。 示例如下：

{% list tabs group=instructions %}


- Swift

  ```swift translate=no
  class NotificationService: UNNotificationServiceExtension {

      var contentHandler: ((UNNotificationContent) -> Void)?
      var bestAttemptContent: UNMutableNotificationContent?

      func activateIfNeeded() {
         // system does not always spawn new process to handle few notification, but AppMetrica ignores second initialization
         let configuration = AppMetricaConfiguration(apiKey: "API-KEY")!
         AppMetrica.activate(with: configuration)

         AppMetricaPush.setExtensionAppGroup(appGroup) // optional, need to send stored events from AppMetricaPush-2.2 and earlier
      }

      override func didReceive(_ request: UNNotificationRequest,
                              withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
         activateIfNeeded()

         AMPAppMetricaPush.handleDidReceive(request)

         self.contentHandler = contentHandler
         bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

         // custom logic

         AppMetrica.sendEventsBuffer()
      }

      override func serviceExtensionTimeWillExpire() {
         bestAttemptContent?()
      }
  }
  ```

- 面向对象的 C

  ```objectivec translate=no
  @implementation NotificationService

  + (void)initialize {
      if ([self class] == [NotificationService class]) {
         AMAAppMetricaConfiguration *configuration =
            [[AMAAppMetricaConfiguration alloc] initWithAPIKey:@"API-KEY"];
         [AMAAppMetrica activateWithConfiguration:configuration];

         [AMPAppMetricaPush setExtensionAppGroup:appGroup]; // push saved events
      }
  }

  - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request
                     withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {

      [AMPAppMetricaPush handleDidReceiveNotificationRequest:request];

      self.contentHandler = contentHandler;
      self.bestAttemptContent = [request.content mutableCopy];

      // custom logic

      [AMAAppMetrica sendEventsBuffer]; // force send all events
  }

  - (void)serviceExtensionTimeWillExpire {
      if (self.bestAttemptContent != nil) {
        self.bestAttemptContent();
      }
  }

  @end
  ```

{% endlist %}

## 第4步。 在 Apple Push Notification Service (APNs) 中注册您的应用 {#apns}

注册会将应用准备好以接收推送通知。 要向 iOS 设备发送通知，请对应用代码做如下修改：

{% list tabs group=instructions %}

- Swift

   ```swift translate=no
   let center = UNUserNotificationCenter.current()
   center.requestAuthorization(options:\[.badge, .alert, .sound\]) { (granted, error) in
     // Enable or disable features based on authorization.
   }
   application.registerForRemoteNotifications()
   ```

   这些数据通常通过以下方法传递：

   ```swift translate=no
   func application(_ application: UIApplication, didFinishLaunchingWithOptions
                    launchOptions: [UIApplicationLaunchOptionsKey :Any]? = nil) -> Bool
   ```

   要了解更多关于使用的方法，请查看文档：`developer.apple.com`

   * [UNUserNotificationCenter.current()](https://developer.apple.com/documentation/usernotifications/unusernotificationcenter/1649510-current)
   * [UNUserNotificationCenter.requestAuthorization(options:completionHandler:)](https://developer.apple.com/documentation/usernotifications/unusernotificationcenter/1649527-requestauthorization)
   * [UIApplication.registerForRemoteNotifications()](https://developer.apple.com/documentation/uikit/uiapplication/1623078-registerforremotenotifications)

- 面向对象的 C

   ```objectivec translate=no
   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];
   ```

   这些数据通常通过以下方法传递：

   ```objectivec translate=no
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
   ```

   要了解更多关于使用的方法，请参阅文档：`developer.apple.com`

   * [[UNUserNotificationCenter currentNotificationCenter]](https://developer.apple.com/documentation/usernotifications/unusernotificationcenter/1649510-currentnotificationcenter?language=objc)
   * [[UNUserNotificationCenter requestAuthorizationWithOptions:completionHandler:]](https://developer.apple.com/documentation/usernotifications/unusernotificationcenter/1649527-requestauthorizationwithoptions?language=objc)
   * [[UIApplication registerForRemoteNotifications]](https://developer.apple.com/documentation/uikit/uiapplication/1623078-registerforremotenotifications?language=objc)

{% endlist %}

## 第5步。 为您的应用注册设备令牌 {#device-token}

要通过 AppMetrica 发送推送通知，需要您的应用设备令牌。 要注册它：

{% list tabs group=instructions %}

- Swift

   将以下代码添加到`AppDelegate`：

   ```swift translate=no
   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)
   }
   ```

- 面向对象的 C

   在你的 `UIApplicationDelegate` 实现中添加以下代码：

   ```objectivec translate=no
   - (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];
   }
   ```

{% endlist %}

要注册设备令牌并发送 APN 环境，请添加以下代码：

{% list tabs group=instructions %}

- Swift

   ```swift translate=no
   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)
   }
   ```

- 面向对象的 C

   ```objectivec translate=no
   - (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];
   }
   ```

{% endlist %}

{% note alert %}

AppMetrica 允许您向 Sandbox APNs 发送推送通知。 但是，如果设备上运行了不同环境的应用版本（_开发_ 和 _生产_），推送通知的处理可能会工作不正常。 为了避免此问题，您可以为_开发_环境使用一个单独的测试 API 密钥。

{% endnote %}

## 第 6 步。 配置处理推送通知的打开 {#opening}

配置处理推送通知打开的方式：

1. 使用代理 `UserNotificationCenterDelegate`/`AMPUserNotificationCenterDelegate`. 它在推送通知被打开时自动处理接收。

   请对代码做如下修改：

   {% list tabs group=instructions %}

   - Swift

      ```swift translate=no
      import UserNotifications

      // In the "func application(_ application: UIApplication, didFinishLaunchingWithOptions
      //                          launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool" method:
      let delegate = AppMetricaPush.userNotificationCenterDelegate
      UNUserNotificationCenter.current().delegate = delegate
      ```

   - 面向对象的 C

      ```objectivec translate=no
      #import <UserNotifications/UserNotifications.h>

      // In the   "- (BOOL)application:(UIApplication *)application
      // didFinishLaunchingWithOptions:(NSDictionary *)launchOptions" method:
      [UNUserNotificationCenter currentNotificationCenter].delegate =
              [AppMetricaPush userNotificationCenterDelegate];
      ```

   {% endlist %}

   要跟踪推送通知的打开情况和其他与之相关的操作，请创建自己的代理，命名为`UNUserNotificationCenterDelegate`，并将其添加到`nextDelegate`：

   {% list tabs group=instructions %}

   - Swift

      ```swift translate=no
      AppMetricaPush.userNotificationCenterDelegate.nextDelegate = yourDelegate
      ```

   - Objective-C

      ```objectivec translate=no
      [AMPAppMetricaPush userNotificationCenterDelegate].nextDelegate = yourDelegate;
      ```

   {% endlist %}

   之后，您可以使用代理的适当方法。

2. 如果您也使用[UISceneDelegate](https://developer.apple.com/documentation/uikit/uiscenedelegate)，请将以下代码添加到`scene(_:willConnectTo:options:)`方法中：

   {% list tabs group=instructions %}

   - Swift

      ```swift translate=no
      func scene(_ scene: UIScene, willConnectTo
                 session: UISceneSession, options
                 connectionOptions: UIScene.ConnectionOptions) {
           AppMetricaPush.handleSceneWillConnectToSession(with: connectionOptions)
      }
      ```

   - Objective-C

      ```objectivec translate=no
      - (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session
            options:(UISceneConnectionOptions *)connectionOptions
      {
          [AMPAppMetricaPush handleSceneWillConnectToSessionWithOptions:connectionOptions];
      }
      ```

   {% endlist %}

## 第 7 步。 (_可选_) 启用推送令牌更新 {#actualization}

如果设备的推送令牌失效（例如用户卸载了应用），APNS 服务可能会返回 410 错误，提示“该设备令牌对于主题已不再有效”。 AppMetrica 可以通过发送静默推送通知来维护有效令牌的列表。 这会让你了解在推送广告活动开始前的设备数量。

要启用此功能，打开Analytics module网页界面，进入应用设置，并选择**使用静默推送通知更新令牌**选项，在**推送通知**标签页中。

使用静默推送通知可以提高推送活动宣传对象评估和推送通知报告的准确性，同时也会影响应用推送通知的成功送达。

## 第 8 步。 (_可选_) 配置上传附件 {#download-file}

{% note info %}

在推送广告的网页界面中，该功能不可用。

{% endnote %}

您可以配置推送通知中附件文件的上传：

1. 通过在 Push SDK 中调用 [downloadAttachmentsForNotificationRequest](https://boost.yandex.com/doc/zh/analytics/content/sdk/ios/push/objectivec/AMPAppMetricaPush.md#method_downloadAttachmentsForNotificationRequest) 方法来配置推送通知中附件文件的上传。 查看集成示例，请参阅文章[上传附件](https://boost.yandex.com/doc/zh/analytics/content/sdk/ios/push/ios-push-download-file.md)。
2. 添加附件（`attachments` 参数），使用 Push API 中的 [发送推送消息](https://boost.yandex.com/doc/zh/analytics/content/mobile-api/push/post-send-batch.md) 操作。

## 发送额外信息 {#send-additional-info}

如果需要，您可以随推送通知一起发送额外信息。 这些数据在Analytics module网页界面中[配置推送活动](https://boost.yandex.com/doc/zh/analytics/content/push/marketing.md)时指定。 要获取这些信息，请使用以下方法：

{% list tabs group=instructions %}

- Swift

   ```swift translate=no
   let userData = AppMetricaPush.userData(forNotification: userInfo)
   ```

- Objective-C

   ```objectivec translate=no
   NSString *userData = [AMPAppMetricaPush userDataForNotification:userInfo];
   ```

{% endlist %}

where `userInfo` 包含有关推送通知的信息。

## 定义通知的接收者 {#detect-internal-push}

AppMetrica 允许你识别<q>自己的</q>推送通知，如果应用程序集成了多个 Push SDK。

要检测 AppMetrica 是否是通知的接收者，请使用以下方法：

{% list tabs group=instructions %}

- Swift

   ```swift translate=no
   let isRelatedToAppMetricaSDK = AppMetricaPush.isNotificationRelated(toSDK: userInfo)
   ```

- Objective-C

   ```objectivec translate=no
   BOOL isRelatedToAppMetricaSDK = [AMPAppMetricaPush isNotificationRelatedToSDK:userInfo];
   ```

{% endlist %}

### 另请参见 {#see-also}

- [库集成示例](https://github.com/yandexmobile/metrica-push-sdk-ios)
- [配置 iOS 应用以发送推送通知](https://boost.yandex.com/doc/zh/analytics/content/sdk/ios/push/ios-settings.md)

<!-- source: zh/analytics/content/_includes/feedback-button-3.md -->
如果您没有找到所需答案，可以通过反馈表单提交您的问题。 请尽可能详细地描述问题。 如果可能，请附上截图。

<a href="../troubleshooting/feedback-new">
  <span class="button">联系支持</span>
</a>

<a href="../troubleshooting/feedback-docs">
  <span class="button">为文档提出改进建议</span>
</a>
<!-- endsource: zh/analytics/content/_includes/feedback-button-3.md -->
