iOS10--消息通知的基本使用

作者: 芝麻绿豆 | 来源:发表于2016-09-20 16:04 被阅读3345次

官方将通知单独放在了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) {                             
  }];
[application registerForRemoteNotifications];

补充:获取授权设置信息

// 获取通知授权和设置    
[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];    
// 设置触发时间     repeats 是否重复  
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:@[@“my_notification”
]];
    [center removeAllDeliveredNotifications];
    - 获取未展示的通知    
[center getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
        NSLog(@"%@",requests);    
}];    
 - 获取展示过的通知    
[center getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) { 
       NSLog(@"%@",notifications);
    }];
  • iOS 10之前的重复设置是repeatInterval 属性,可以按年、月、日、星期等规律设置重复时间,例如:
    NSCalendarUnitWeekday
    NSCalendarUnitWeekOfMonth
    NSCalendarUnitDay
    NSCalendarUnitMonth
  • iOS 10之后repeatInterval设置:
triggerWithRegion:repeats:
triggerWithTimeInterval:repeats:
triggerWithDateMatchingComponents:repeats:

说明:repeats 是布尔类型,无法设置重复类型;其实他是根据你传入的值确定下一次触发的时间,例如:

        NSCalendar *calendar = [NSCalendar currentCalendar];
        calendar.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"];
        NSDateComponents* comps = [[NSDateComponents alloc] init];
        NSInteger unitFlags =NSCalendarUnitWeekday|
        NSCalendarUnitHour |NSCalendarUnitMinute |NSCalendarUnitSecond ;
        comps = [calendar components:unitFlags fromDate:time];
        UNCalendarNotificationTrigger *trigger_1 = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:comps repeats:YES];

**注意** 如果你希望是按星期重复NSCalendarUnit 就设置NSCalendarUnitWeekday;如果按月重复设置NSCalendarUnitDay;如果同时出现NSCalendarUnitWeekday、NSCalendarUnitYear、NSCalendarUnitMonth、NSCalendarUnitDay下一次的触发时间就会混乱 无规律可寻;

  • 远程通知的格式:

{ "aps":{ "alert":{ "title":"I am title", "subtitle":"I am subtitle", "body":"I am body" }, "sound":"default", "badge":1 } }

具体请参考官方文档

    [center addNotificationRequest:request_1 withCompletionHandler:^(NSError * _Nullable error) {       
    }];
接收通知
center.delegate = self;
- 应用内展示通知:
 - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
   // 如果不想显示某个通知,可以直接用空 options 调用 completionHandler: // completionHandler([])

    completionHandler(UNNotificationPresentationOptionBadge + UNNotificationPresentationOptionSound);   
}
- 在用户与你推送的通知进行交互时被调用:
 - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{    
completionHandler();       
NSLog(@"userInfo--%@",response.notification.request.content.userInfo);
}

UNNotificationCategory的应用:

  • 创建一个 category:
/*     
UNNotificationActionOptionAuthenticationRequired = (1 << 0),    
UNNotificationActionOptionDestructive = (1 << 1), 取消     
UNNotificationActionOptionForeground = (1 << 2), 启动程序     
*/   
 UNTextInputNotificationAction *textAction = [UNTextInputNotificationAction actionWithIdentifier:@"my_text" title:@"text_action" options:UNNotificationActionOptionForeground textInputButtonTitle:@"输入" textInputPlaceholder:@"默认文字"];    
UNNotificationAction *action = [UNNotificationAction actionWithIdentifier:@"my_action" title:@"action" options:UNNotificationActionOptionDestructive];    
UNNotificationAction *action_1 = [UNNotificationAction actionWithIdentifier:@"my_action_1" title:@"action_1" options:UNNotificationActionOptionAuthenticationRequired];    
/*     
UNNotificationCategoryOptionNone = (0),     
UNNotificationCategoryOptionCustomDismissAction = (1 << 0),     
UNNotificationCategoryOptionAllowInCarPlay = (2 << 0),     
*/    
UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"my_category" actions:@[textAction,action,action_1] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];    
NSSet *setting = [NSSet setWithObjects:category, nil];    
[center setNotificationCategories:setting];
  • 在创建 UNNotificationContent 时把 categoryIdentifier 设置为需要的 category id 即可:
content.categoryIdentifier = @"my_category";

远程推送也可以使用 category,只需要在 payload 中添加 category 字段,并指定预先定义的 category id 就可以了

  • 处理category的通知:
 - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{    
    completionHandler();       
    NSLog(@"userInfo--%@",response.notification.request.content.userInfo);       
// 获取通知中心的所有的Categories    
[center getNotificationCategoriesWithCompletionHandler:^(NSSet<UNNotificationCategory *> * _Nonnull categories) { 
              for (UNNotificationCategory *category in categories) { 
           if ([category.identifier isEqualToString:@"my_category"] && [response.notification.request.content.categoryIdentifier isEqualToString:@"my_category"]) { 
                  for (UNNotificationAction *textAction in category.actions) {
                           if ([textAction.identifier isEqualToString:@"my_text"]) { 
                                         UNTextInputNotificationAction *text = (UNTextInputNotificationAction *)textAction;
                                         UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:text.textInputButtonTitle preferredStyle:UIAlertControllerStyleAlert];
                                        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]]; 
                                        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
                            }
                } 
           }
        }
 }];
}
长按 3D touch 效果图
进入应用
iOS 10 中被标为弃用的 API

UILocalNotification
UIMutableUserNotificationAction
UIMutableUserNotificationCategory
UIUserNotificationAction
UIUserNotificationCategory
UIUserNotificationSettings
handleActionWithIdentifier:forLocalNotification:
handleActionWithIdentifier:forRemoteNotification:
didReceiveLocalNotification:withCompletion:
didReceiveRemoteNotification:withCompletion:

相关文章

  • iOS10--消息通知的基本使用

    官方将通知单独放在了UserNotifications.framework,使用时需要导入框架。UserNotif...

  • iOS通知原理解析

    一、通知的基本使用 1、基本概念 NSNotification 是iOS中一个调度消息通知的类,采用单例模式设计,...

  • 如何使用消息通知?

    之前有运营主问粉丝君:只有进入粉丝圈才能收到消息吗?当然不是啦! 消息通知功能可以让用户第一时间在你的公众号收到被...

  • iOS-Notification 实现原理详解

    目录 一 通知的基本使用基本概念什么情况下使用通知应用场景如何使用通知使用通知需要注意的细节二 通知实现的原理概述...

  • Laravel 消息通知的使用

    https://learnku.com/docs/laravel/5.8/notifications/3921 创...

  • 消息通知推送

    我们在设计产品时会涉及到消息通知的功能,消息通知一般采用消息推送系统来进行处理。 消息通知的基本功能 点对点的消息...

  • 通知基本使用篇

    通知是您可以在应用的常规 UI 外部向用户显示的消息。当您告知系统发出通知时,它将先以图标的形式显示在通知区域中。...

  • Android学习系列之-通知Notification

    今天打算介绍下通知的基本使用方法。首先,看下官网的介绍。 通知是可以在应用的常规 UI 外部向用户显示的消息。当您...

  • 微信公众平台开发 微信模板消息发送

    嗨:大家好,今天咱们使用微信的时候经常能收到微信的购买消息的通知,这些消息通知很多使用的是模板消息,模板消息比较图...

  • 消息通知泛型版

    最近在做一个项目,项目内部需要使用消息通知系统,由于只是单机内部消息通知,使用类似kafka这样的消息队列就太重量...

网友评论

  • 洁简:定义的UNNotificationAction不显示什么原因
  • kinmo:楼主,官方的定时推送代码是
    NSDateComponents* date = [[NSDateComponents alloc] init];
    date.hour = 8;
    date.minute = 30;
    UNCalendarNotificationTrigger* trigger = [UNCalendarNotificationTrigger
    triggerWithDateMatchingComponents:date repeats:YES];
    不过用起来会在每天8点的时候一分钟调用一次。
    芝麻绿豆:@July丶ye 建议你打印一下 设置信息 看设置的是否正确
    kinmo:@芝麻绿豆 是的,可是每天到了8点就会一分钟提醒一次...不知道是什么bug
    芝麻绿豆:@July丶ye 你这定得不是每天8半重复提醒吗?
  • DZIR:请问在锁屏状态下的通知能自定义吗?
  • 请叫我小陈陈:留下个demo就更好了
  • Nick菠萝:很厉害很厉害~

本文标题:iOS10--消息通知的基本使用

本文链接:https://www.haomeiwen.com/subject/qwkoettx.html