MST
星途 面试题库

面试题:Objective-C中User Notifications框架如何设置通知的触发时间?

在Objective-C的User Notifications用户通知框架下,描述如何创建并设置一个定时触发的本地通知,需要指出关键的类和方法。
43.7万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试
  1. 关键类

    • UNUserNotificationCenter:用于管理本地和远程通知的中心类,负责注册通知类型、发送通知、处理通知相关的回调等操作。
    • UNMutableNotificationContent:用于创建通知内容,可设置标题、副标题、正文、附件等信息。
    • UNTimeIntervalNotificationTrigger:用于创建基于时间间隔触发的通知触发器。
  2. 实现步骤及关键方法

    • 注册通知类型
      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.");
          }
      }];