跳转至

推送通知

概述

本指南介绍了如何集成 iOS 的推送通知,以及如何将 UNNotificationServiceExtension 添加到 Xcode 项目中以在通知中显示图像。

开始之前

注册远程通知

在启动时或应用程序流程的所需点注册您的应用程序以接收远程通知。

您可以手动注册远程推送通知,并使用 UNUserNotificationCenterDelegate 协议方法来处理传入的通知。

此外,SDK 还通过调用 [SohaSDK requestPushNotification] 方法来帮助您执行这些操作。

以下,我们提供了两种不同方式的说明,供您参考:
- 方法 1:手动
- 方法 2:使用 SDK 的方法

方法 1:手动

步骤 1:注册远程通知
[UNUserNotificationCenter currentNotificationCenter].delegate = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
    if( !error ) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication] registerForRemoteNotifications];
        });
    } else {
         NSLog( @"ERROR: %@ - %@", error.localizedFailureReason, error.localizedDescription );
    }
}];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
步骤 2:处理通知中心的委托。
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler{
    [SohaSDK didReceiveNotificationResponse:response];
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    [SohaSDK willPresentNotification:notification];
}

Tip

为了简化和避免手动处理代码片段,使用 requestPushNotification 方法。

方法 2:使用 SDK 的方法

SDK 提供了一个封装方法,简化了集成过程。只需调用以下方法:

[SohaSDK requestPushNotification];
通过调用此方法,将执行封装的代码,并在内部处理任何必要的集成步骤。此方法将负责注册远程推送通知并处理通知中心的委托,使您可以专注于使用 SDK 的功能,无需手动代码处理

访问注册令牌

实现 application(_:didRegisterForRemoteNotificationsWithDeviceToken:) 方法以检索 APNs 令牌,然后调用 SohaSDK registerDeviceToken:

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [SohaSDK registerDeviceToken:deviceToken];
}