面试题答案
一键面试- 涉及的类与方法
- UNUserNotificationCenter:负责管理通知的中心类。其中
+ (UNUserNotificationCenter *)currentNotificationCenter
方法用于获取当前的通知中心实例。 - UNNotificationResponse:表示用户对通知的响应。通过它可以获取到通知的相关信息。在处理通知点击时,会通过该类获取自定义数据。
- AppDelegate:应用程序的代理类,在其中处理通知点击事件。具体涉及到
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler
方法。
- UNUserNotificationCenter:负责管理通知的中心类。其中
- 实现步骤
- 创建通知时添加自定义数据:
在创建通知请求(
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
来告知系统已经完成对通知响应的处理。