一、创建本地通知事例详解
首先本地推送分为iOS10之前的版本 和 之后的版本
iOS之后的版本 有一些新的功能
首先申请权限不区分本地和远程推送了
利用独立的UserNotifications.framework
框架来管理通知;并且增加了撤销单条通知、更新已展示通知、中途修改通知内容等等,以及在通知中展示图片视频,自定义通知UI等一系列新功能;总之,iOS 10的通知功能十分强大。
iOS10之后的授权
// 获取通知授权和设置
[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(@"已授权");
}
}];
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) {
}];
iOS10之前的授权
// 注册本地通知
UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge) categories:nil];
//注册通知
[[UIApplication sharedApplication] registerUserNotificationSettings:setting];
iOS10之后的本地通知的创建
- (void)creatLocalPushIOS10{
//注册
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
// [center setDelegate:self]; 这里如果设置了代理 就不会走之前的appdelegate里面的didReceiveLocalNotification方法了 就走代理的方法 如果不设置还是会默认走之前的didReceiveLocalNotification方法
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge |UNAuthorizationOptionSound ) completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) {
NSLog(@"授权成功");
}else {
NSLog(@"没有授权");
}
}];
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
NSLog(@"%@",settings);
}];
// 创建本地通知也需要在appdelegate中心进行注册
// 1.创建通知内容
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.title = @"本地通知标题";
content.subtitle = @"本地通知副标题";
content.body = @"本地通知内容";
content.badge = @1;
NSError *error = nil;
NSString *path = [[NSBundle mainBundle] pathForResource:@"imageName@2x" ofType:@"png"];
// 2.设置通知附件内容
NSMutableDictionary *optionsDict = [NSMutableDictionary dictionary];
// 一个包含描述文件的类型统一类型标识符(UTI)一个NSString。如果不提供该键,附件的文件扩展名来确定其类型,常用的类型标识符有 kUTTypeImage,kUTTypeJPEG2000,kUTTypeTIFF,kUTTypePICT,kUTTypeGIF ,kUTTypePNG,kUTTypeQuickTimeImage等。
// 需要导入框架 #import
optionsDict[UNNotificationAttachmentOptionsTypeHintKey] = (__bridge id _Nullable)(kUTTypeImage);
// 是否隐藏缩略图
// optionsDict[UNNotificationAttachmentOptionsThumbnailHiddenKey] = @YES;
// 剪切缩略图
optionsDict[UNNotificationAttachmentOptionsThumbnailClippingRectKey] = (__bridge id _Nullable)((CGRectCreateDictionaryRepresentation(CGRectMake(0.25, 0.25, 0.5 ,0.5))));
// 如果附件是影片,则以第几秒作为缩略图
// optionsDict[UNNotificationAttachmentOptionsThumbnailTimeKey] = @1;
// optionsDict如果不需要,可以不设置,直接传nil即可
UNNotificationAttachment *att = [UNNotificationAttachment attachmentWithIdentifier:@"identifier" URL:[NSURL fileURLWithPath:path] options:optionsDict error:&error];
if (error) {
NSLog(@"attachment error %@", error);
}
content.attachments = @[att];
content.launchImageName = @"imageName@2x";
// 2.设置声音
UNNotificationSound *sound = [UNNotificationSound defaultSound];
content.sound = sound;
// 3.触发模式 多久触发,是否重复
// 3.1 按秒 这里如果设置为YES 那么时间间隔必须大于60秒 否则会崩溃报错
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:61 repeats:YES];
// 3.2 按日期
// // 周二早上 9:00 上班
// NSDateComponents *components = [[NSDateComponents alloc] init];
// // 注意,weekday是从周日开始的计数的
// components.weekday = 3;
// components.hour = 9;
// UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];
// 3.3 按地理位置
// 一到某个经纬度就通知,判断包含某一点么
// 不建议使用!!!!!!CLRegion *region = [[CLRegion alloc] init];
// CLCircularRegion *circlarRegin = [[CLCircularRegion alloc] init];
// // 经纬度
// CLLocationDegrees latitudeDegrees = 123.00; // 维度
// CLLocationDegrees longitudeDegrees = 123.00; // 经度
//
// [circlarRegin containsCoordinate:CLLocationCoordinate2DMake(latitudeDegrees, longitudeDegrees)];
// UNLocationNotificationTrigger *trigger = [UNLocationNotificationTrigger triggerWithRegion:circlarRegin repeats:NO];
// 4.设置UNNotificationRequest
NSString *requestIdentifer = @"TestRequest";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifer content:content trigger:trigger];
//5.把通知加到UNUserNotificationCenter, 到指定触发点会被触发
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
NSLog(@"添加成功");
}];
}
//代理方法如下
//Ios 10之后如果设置了代理 就会走这个方法
#pragma mark - UNUserNotificationCenterDelegate
// iOS10 推送回调
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
NSDictionary *userInfo = notification.request.content.userInfo;
UNNotificationRequest *request = notification.request; // 收到推送的请求
UNNotificationContent *content = request.content; //收到推送消息的全部内容
NSNumber *badge = content.badge; // 推送消息的角标
NSString *body = content.body; // 收到推送消息具体内容
UNNotificationSound *sound = content.sound; //声音
NSString *subTitle = content.subtitle; // 推送收到的副标题
NSString *title = content.title; // 推送收到的标题
if ([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
NSLog(@"iOS10 收到远程通知");
}else{
NSLog(@"ios10 收到本地通知%@%@%@%@%@",title,subTitle,body,badge,userInfo);
}
completionHandler(UNNotificationPresentationOptionBadge |
UNNotificationPresentationOptionSound |
UNNotificationPresentationOptionAlert );
// 需要执行此方法,选择是否提醒用户,有以上三种那个类型可选
}
// 通知的点击事件
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
NSDictionary *userInfo = response.notification.request.content.userInfo;
UNNotificationRequest *request = response.notification.request;
UNNotificationContent *content = request.content; //收到推送消息的全部内容
NSNumber *badge = content.badge; // 推送消息的角标
NSString *body = content.body; // 收到推送消息具体内容
UNNotificationSound *sound = content.sound; //声音
NSString *subTitle = content.subtitle; // 推送收到的副标题
NSString *title = content.title; // 推送收到的标题
NSLog(@">>>通知的点击事件");
if ([request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
NSLog(@"iOS10 收到远程通知");
}else{
NSLog(@"ios10 收到本地通知%@%@%@%@%@",title,subTitle,body,badge,userInfo);
}
completionHandler(); //系统要求执行此方法
}
iOS10后的补充
UserNotifications提供了三种触发器:
UNTimeIntervalNotificationTrigger :一定时间后触发
UNCalendarNotificationTrigger : 在某月某日某时触发
UNLocationNotificationTrigger : 在用户进入或是离开某个区域时触发
- 移除还未展示的通知
[center removePendingNotificationRequestsWithIdentifiers: @[@“rjb_notification”
]];
[center removeAllPendingNotificationRequests]; // - (void)cancelAllLocalNotifications;
- 移除已经展示过的通知
[center removeDeliveredNotificationsWithIdentifiers:@[@“ rjb_notification”
]];
[center removeAllDeliveredNotifications];
- 获取未展示的通知
[center getPendingNotificationRequestsWithCompletionHandler:^(NSArray * _Nonnull requests) {
NSLog(@"%@",requests);
}];
- 获取展示过的通知
[center getDeliveredNotificationsWithCompletionHandler:^(NSArray * _Nonnull notifications) {
NSLog(@"%@",notifications);
}];
demo 地址: https://github.com/rjb0514/LocalNotification
参考:https://www.cnblogs.com/fishbay/p/7206827.html
https://www.jianshu.com/p/3d602a60ca4f