官方将通知单独放在了UserNotifications.framework,使用时需要导入框架。
UserNotifications.framework主要类文件:
UNCalendarNotificationTrigger
UNLocationNotificationTrigger
UNMutableNotificationContent
UNNotification
UNNotificationAction
UNNotificationAttachment
UNNotificationCategory
UNNotificationContent
UNNotificationRequest
UNNotificationResponse
UNNotificationServiceExtension
UNNotificationSettings
UNNotificationSound
UNNotificationTrigger
UNPushNotificationTrigger
UNTextInputNotificationAction
UNTextInputNotificationResponse
UNTimeIntervalNotificationTrigger
UNUserNotificationCenter
UNUserNotificationCenter的应用:
- 请求用户授权:
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter]; // 请求授权 /* UNAuthorizationOptionBadge = (1 << 0), UNAuthorizationOptionSound = (1 << 1), UNAuthorizationOptionAlert = (1 << 2), UNAuthorizationOptionCarPlay = (1 << 3), */ [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound + UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) { if(granted){
if(granded)
//同意
}else{
//不同意
}}];
补充:
获取授权设置信息
// 获取通知授权和设置 [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { /* UNAuthorizationStatusNotDetermined : 没有做出选择 UNAuthorizationStatusDenied : 用户未授权 UNAuthorizationStatusAuthorized :用户已授权 */ if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) { NSLog(@"未选择"); }else if (settings.authorizationStatus == UNAuthorizationStatusDenied){ NSLog(@"未授权"); }else if (settings.authorizationStatus == UNAuthorizationStatusAuthorized){ NSLog(@"已授权"); } }]
-
创建本地通知:
// 创建一个本地通知 UNMutableNotificationContent *content_1 = [[UNMutableNotificationContent alloc] init]; // 主标题 content_1.title = [NSString localizedUserNotificationStringForKey:@"title" arguments:nil]; // 副标题 content_1.subtitle = [NSString localizedUserNotificationStringForKey:@"subtitle" arguments:nil]; content_1.badge = [NSNumber numberWithInteger:1]; content_1.body = [NSString localizedUserNotificationStringForKey:@"title_message_for_yan" arguments:nil]; content_1.sound = [UNNotificationSound defaultSound]; // 设置触发时间 UNTimeIntervalNotificationTrigger *trigger_1 = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO]; // 创建一个发送请求 UNNotificationRequest *request_1 = [UNNotificationRequest requestWithIdentifier:@"my_notification" content:content_1 trigger:trigger_1];
补充:
- UserNotifications提供了三种触发器:
UNTimeIntervalNotificationTrigger :一定时间后触发 UNCalendarNotificationTrigger : 在某月某日某时触发 UNLocationNotificationTrigger : 在用户进入或是离开某个区域时触发
- @“my_notification”请求的标识符可以用来管理通知:
- 移除还未展示的通知 [center removePendingNotificationRequestsWithIdentifiers: @[@“my_notification”]]; [center removeAllPendingNotificationRequests]; // - (void)cancelAllLocalNotifications; - 移除已经展示过的通知 [center removeDeliveredNotificationsWithIdentifiers:
- UserNotifications提供了三种触发器: