MST

星途 面试题库

面试题:Objective-C实现Mac OS通知中心的本地通知定制

使用Objective-C编写代码实现Mac OS通知中心的本地通知,要求能够自定义通知的触发时间、显示内容(包括图片和富文本),并处理用户点击通知后的响应逻辑。
38.2万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试

以下是使用Objective-C实现Mac OS通知中心本地通知的代码示例:

  1. 导入必要的框架 在你的项目中,需要导入UserNotifications框架来处理通知相关的操作。
#import <UserNotifications/UserNotifications.h>
  1. 请求通知权限 在应用启动时,请求用户授予通知权限。
- (void)requestAuthorization {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound + UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            NSLog(@"Notification authorization granted.");
        } else {
            NSLog(@"Notification authorization failed: %@", error);
        }
    }];
}
  1. 创建并设置本地通知
- (void)scheduleLocalNotification {
    // 创建通知内容
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = @"自定义通知标题";
    content.body = @"这是自定义通知的内容";
    content.sound = [UNNotificationSound defaultSound];
    content.badge = @(1);
    
    // 添加图片附件(假设图片在bundle中)
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"example" ofType:@"jpg"];
    NSURL *imageURL = [NSURL fileURLWithPath:imagePath];
    UNNotificationAttachment *imageAttachment = [UNNotificationAttachment attachmentWithIdentifier:@"image" URL:imageURL options:nil error:nil];
    content.attachments = @[imageAttachment];
    
    // 添加富文本
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"这是一段富文本内容"];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, attributedString.length)];
    content.threadIdentifier = @"richTextThread";
    
    // 设置触发时间(例如5秒后触发)
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
    
    // 创建通知请求
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"localNotification" content:content trigger:trigger];
    
    // 调度通知
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (error) {
            NSLog(@"Error scheduling notification: %@", error);
        } else {
            NSLog(@"Notification scheduled successfully.");
        }
    }];
}
  1. 处理用户点击通知后的响应逻辑 在AppDelegate中实现userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:方法来处理用户点击通知后的操作。
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    if ([response.notification.request.identifier isEqualToString:@"localNotification"]) {
        NSLog(@"User clicked on the local notification.");
        // 在这里添加你的处理逻辑,例如打开特定页面等
    }
    completionHandler();
}

application:didFinishLaunchingWithOptions:方法中调用requestAuthorizationscheduleLocalNotification方法:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self requestAuthorization];
    [self scheduleLocalNotification];
    return YES;
}

这样,就实现了Mac OS通知中心的本地通知,包括自定义触发时间、显示内容(图片和富文本)以及处理用户点击通知后的响应逻辑。