MST
星途 面试题库

面试题:Objective-C的User Notifications框架中如何处理通知的交互并传递自定义数据?

假设你使用Objective-C的User Notifications框架创建了一个通知,当用户点击通知后,如何将一些自定义数据传递到应用程序中进行处理?详细说明涉及到的类、方法以及实现步骤。
41.1万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试
  1. 涉及的类与方法
    • UNUserNotificationCenter:负责管理通知的中心类。其中+ (UNUserNotificationCenter *)currentNotificationCenter方法用于获取当前的通知中心实例。
    • UNNotificationResponse:表示用户对通知的响应。通过它可以获取到通知的相关信息。在处理通知点击时,会通过该类获取自定义数据。
    • AppDelegate:应用程序的代理类,在其中处理通知点击事件。具体涉及到- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler方法。
  2. 实现步骤
    • 创建通知时添加自定义数据: 在创建通知请求(UNNotificationRequest)时,可以通过userInfo字典来添加自定义数据。例如:
NSDictionary *userInfo = @{@"customKey": @"customValue"};
UNMutableNotificationContent *content = [UNMutableNotificationContent new];
content.title = @"My Notification";
content.body = @"This is a test notification";
content.userInfo = userInfo;
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"myNotification" content:content trigger:trigger];
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    if (error) {
        NSLog(@"Error adding notification request: %@", error);
    }
}];
  • 处理通知点击事件: 在AppDelegate中实现userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:方法,从response.notification.request.content.userInfo中获取自定义数据。示例代码如下:
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    NSString *customValue = userInfo[@"customKey"];
    NSLog(@"Received custom value: %@", customValue);
    completionHandler();
}

在上述代码中,先从response获取通知的content,进而获取userInfo字典,从中取出自定义数据。最后调用completionHandler来告知系统已经完成对通知响应的处理。