通知处理接口

更新时间:2025-03-25 11:59:41

本文档介绍如何在iOS应用中处理通知。

通知简介

通知是由苹果服务器推送到用户设备的消息,可以在锁屏状态下展示。接收通知不要求用户的App保持在线,只需设备连接到网络即可接收和显示通知。

通知处理

由于iOS系统的限制,通知不会默认交给应用处理。需要根据不同类型的通知进行分别处理。以下是几种常见的通知处理场景:

前台通知回调

App处于前台时,系统会通过开发者实现的代理方法将通知回调给应用。开发者可以在该方法中执行相关逻辑,并决定是否展示通知。

点击通知回调

用户点击通知后,系统会打开App并回调开发者实现的代理方法,以处理点击事件。

静默通知回调

当发送静默通知时,系统会在App处于前台或后台时,将通知回调给开发者实现的代理方法。

代码示例

Swift
Object C
import UIKit
import CloudPushSDK
import UserNotifications

@main
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // 初始化SDK
        // ......
        
        // 设置通知中心代理
        UNUserNotificationCenter.current().delegate = self
        
        return true
    }
    
    // MARK: - UNUserNotificationCenterDelegate
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, 
                              willPresent notification: UNNotification,
                              withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("收到前台通知回调")
        handleUserInfo(userInfo: notification.request.content.userInfo)
        
        // 设置通知展示方式
        completionHandler([.alert, .sound])
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
        print("收到点击通知回调")
        handleUserInfo(userInfo: response.notification.request.content.userInfo)
        completionHandler()
    }
    
    func application(_ application: UIApplication,
                   didReceiveRemoteNotification userInfo: [AnyHashable : Any],
                   fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("收到静默通知回调")
        handleUserInfo(userInfo: userInfo)
        completionHandler(.newData)
    }
    
    func handleUserInfo(userInfo: [AnyHashable : Any]) {
        // 通过字典获取通知携带的自定义kv,例如:
        // let customValue = userInfo["customKey"] as? String
        
        guard let aps = userInfo["aps"] as? [String: Any],
              let alert = aps["alert"] as? [String: String],
              let title = alert["title"],
              let body = alert["body"] else {
            return
        }
        
        print("通知内容: title=\(title), body=\(body)")
        
        // 通知点击上报
        CloudPushSDK.sendNotificationAck(userInfo)
    }
    
    // ......
}
#import "AppDelegate.h"
#import "CloudPushSDK/CloudPushSDK.h"
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate () <UNUserNotificationCenterDelegate>
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 初始化SDK
    // ......
    
    // 设置通知中心代理
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    
    return YES;
}

#pragma mark - 接收通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    NSLog(@"收到前台通知回调");
    [self handleUserInfo:notification.request.content.userInfo];

    // 这里开发者可以根据需要决定是否弹出通知
    completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    NSLog(@"收到点击通知回调");
    [self handleUserInfo:response.notification.request.content.userInfo];
    completionHandler();
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"收到静默通知回调");
    [self handleUserInfo:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)handleUserInfo:(NSDictionary *)userInfo {
    // 可以通过字典获取通知携带的自定义kv,例如:
    // NSString *customValue = userInfo[@"customKey"];
    
    NSString *title = userInfo[@"aps"][@"alert"][@"title"];
    NSString *body = userInfo[@"aps"][@"alert"][@"body"];
    NSLog(@"通知内容: title=%@, body=%@", title, body);
    
    // 通知点击上报
    [CloudPushSDK sendNotificationAck:userInfo];
}

// ......
@end

userInfo对象

示例代码中的userInfo对象是通知回调中传递的字典,格式如下:

{
  "aps" : {
    "category" : "test_category",
    "badge" : 2,
    "sound" : "default",
    "interruption-level" : "active",
    "relevance-score" : 0.5,
    "alert" : {
      "title" : "notification title",
      "subtitle" : "this is notification subtitle",
      "body" : "this is notification body"
    },
    "thread-id" : "test_thread_id"
  },
  "i" : 11153971268435968,
  "customKey1" : "customValue1",
  "customKey2" : "customValue2"
}

其中apsAPNs协议负载,i字段是阿里云推送消息ID,customKey是用户通过阿里云推送接口指定的自定义字段iOSExtParameters

  • 本页导读 (0)
  • 通知简介
  • 通知处理
  • 前台通知回调
  • 点击通知回调
  • 静默通知回调
  • 代码示例