面试题答案
一键面试-
关键类:
UNUserNotificationCenter
:用于管理本地和远程通知的中心类,负责注册通知类型、发送通知、处理通知相关的回调等操作。UNMutableNotificationContent
:用于创建通知内容,可设置标题、副标题、正文、附件等信息。UNTimeIntervalNotificationTrigger
:用于创建基于时间间隔触发的通知触发器。
-
实现步骤及关键方法:
- 注册通知类型:
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; UNAuthorizationOptions options = UNAuthorizationOptionAlert + UNAuthorizationOptionSound + UNAuthorizationOptionBadge; [center requestAuthorizationWithOptions:options completionHandler:^(BOOL granted, NSError * _Nullable error) { if (granted) { NSLog(@"Notification authorization granted."); } else { NSLog(@"Notification authorization denied."); } }];
- 创建通知内容:
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; content.title = [NSString localizedUserNotificationStringForKey:@"Notification Title" arguments:nil]; content.subtitle = [NSString localizedUserNotificationStringForKey:@"Notification Subtitle" arguments:nil]; content.body = [NSString localizedUserNotificationStringForKey:@"Notification Body" arguments:nil]; content.sound = [UNNotificationSound defaultSound];
- 创建定时触发的通知触发器:
// 例如设置5秒后触发 UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
- 创建通知请求:
NSString *identifier = @"com.example.notification"; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
- 添加通知请求到通知中心:
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (error) { NSLog(@"Error adding notification request: %@", error); } else { NSLog(@"Notification request added successfully."); } }];
- 注册通知类型: