局部发送通知

在iOS开发中,局部通知(Local Notification)是一种重要的功能,它允许应用在特定时间或触发特定事件时向用户发送提醒,即使应用没有在前台运行也能完成。局部通知的使用广泛,例如定时提醒、日程安排、消息更新等场景。本文将深入探讨如何在iOS中实现局部通知,并提供相关的代码示例。一、局部通知概念局部通知是由应用程序自身创建并管理的,不需要网络连接即可在本地设备上触发。与远程通知(Remote Notification)不同,远程通知通常由服务器发送,而局部通知完全由应用控制。局部通知可以包括标题、副标题、声音、附加数据等元素,以提供丰富的用户交互体验。二、配置通知你需要在Info.plist文件中添加权限请求,允许应用发送通知。添加以下键值对: ```xml NSUserNotificationUsageDescription 需要您的许可才能发送重要通知。 ```三、设置通知中心代理在你的AppDelegate.m或AppDelegate.swift文件中,设置UNUserNotificationCenter的代理: Objective-C: ```objc #import - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; center.delegate = self; [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) { if (!error) { //授权成功} }]; return YES; } ``` Swift: ```swift import UserNotifications func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let center = UNUserNotificationCenter.current() center.delegate = self center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in if error == nil { //授权成功} } return true } ```四、创建通知内容定义一个UNMutableNotificationContent对象,设置通知的标题、副标题、声音等属性: Objective-C: ```objc UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; content.title = @"局部通知"; content.body = @"这是一个测试通知,用于演示局部通知的发送"; content.sound = [UNNotificationSound defaultSound]; ``` Swift: ```swift let content = UNMutableNotificationContent() content.title = "局部通知" content.body = "这是一个测试通知,用于演示局部通知的发送" content.sound = .default ```五、设置通知触发器局部通知的触发可以基于时间、地理位置或其他条件。这里以基于时间的触发为例: Objective-C: ```objc NSDateComponents *dateComponents = [[NSDateComponents alloc] init]; dateComponents.hour = 20; //设置为晚上8点dateComponents.minute = 30; UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateComponents repeats:YES]; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"testNotification" content:content trigger:trigger]; [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (!error) { //请求添加成功} }]; ``` Swift: ```swift let dateComponents = DateComponents(hour: 20, minute: 30) let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) let request = UNNotificationRequest(identifier: "testNotification", content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) { (error) in if error == nil { //请求添加成功} } ```六、处理通知响应实现UNUserNotificationCenterDelegate协议的相关方法,处理用户对通知的响应: Objective-C: ```objc - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler { NSLog(@"用户点击了通知:%@", response.notification.request.content.title); completionHandler(); } - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { //当通知在前台显示时,决定是否显示提醒completionHandler(UNNotificationPresentationOptionAlert); } ``` Swift: ```swift extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print("用户点击了通知:(response.notification.request.content.title)") completionHandler() } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { //当通知在前台显示时,决定是否显示提醒completionHandler([.alert]) } } ```至此,你已经成功地实现了iOS中的局部通知。你可以通过修改日期组件来设置不同的触发时间,或者根据需求创建不同的通知请求。局部通知是iOS应用与用户保持互动的重要工具,合理利用它可以提升用户体验。记得在实际开发中,尊重用户的隐私权,适时适当地发送通知。
zip 文件大小:24.45KB