免费开源的iOS开发学习平台

本地消息推送(基于iOS10 UserNotifications框架):4-UNUserNotificationCenterDelegate代理协议

UNUserNotificationCenterDelegate是UNUserNotificationCenter类中定义的代理协议,其提供了当用户对消息推送进行交互时可以调用的方法。

UNUserNotificationCenterDelegate

UNUserNotificationCenterDelegate中定义了如下两个代理协议方法。

  • 当终端即将展示推送消息时,会调用willPresentNotification:方法
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler;

我们编写了一个示例代码,每60秒发送一次提醒,如下图所示,不论用户是否打开该推送消息,willPresentNotification:方法每60秒会被自动调用一次。

  • 当用户点击推送消息,打开App时, didReceiveNotificationResponse:方法会被调用
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler

如下图所示,当用户点击推送消息时,didReceiveNotificationResponse:方法会被调用。

获取推送中携带的信息

在UNUserNotificationCenterDelegate协议定义的代理方法中,可以获取notification(UNNotification类)以及response(UNNotificationResponse类)参数,通过这两个参数,我们都可以获取到携带推送信息的content(UNNotificationContent类)对象。

如下所示,我们可以通过response获取content对象。

-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    NSLog(@"%s",__func__);
    //获取**content**对象
    UNNotificationContent * content = response.notification.request.content;
    NSLog(@"notification body:%@",content.body);
    NSLog(@"notification subtitle:%@",content.subtitle);
    NSLog(@"notification title:%@",content.title);
    
}

注意点

在实现UNUserNotificationCenterDelegate协议中的方法之前,不要忘记设置代理对象以及设置遵守代理协议。(以AppDelegate为例)

  • 设置遵守代理协议
#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>
@interface AppDelegate ()<UNUserNotificationCenterDelegate>
@end
  • 设置代理对象
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    //设置代理对象
    center.delegate = self;
    return YES;
}