userwatchnotificationss 兼容之前版本吗

之前说会单独整理消息通知的内容,但是因为工(就)作(是)的(很)事(懒)没有更新文章,违背了自己的学习的初衷。因为互联网一定要有危机意识,说不定眼一睁,我们就out丢了饭碗。
图片来源网络.jpeg
“狼,他没有狮子老虎强壮,也没有大象那庞大的身躯,但至少:我从来没在马戏团看到过他们的身影。”
也许只有狼在一直奔跑,这是我一直喜欢它的原因,要像狼一样不断奔跑,才能幸存!
看完楼主装的一手好X,我来总结一点点你都知道的通知方面的知识点!
楼主装逼,打他.jpg
iOS10 新特性一出,各个大神就早已研究新特性能给场景智能化所带来的好处(唉,可惜我只是一个小白)。我也被安排适配iOS10的推送工作!
Apple 表示这是 iOS 有史以来最大的升级(our biggest release yet),更加智能开放的 Siri 、强化应用对 3D Touch 支持、 HomeKit 、电话拦截及全新设计的通知等等…
iOS 10 中将之前繁杂的推送通知统一成UserNotifications.framework 来集中管理和使用通知功能,还增加一些实用的功能——撤回单条通知、更新已展示通知、中途修改通知内容、在通知中显示多媒体资源、自定义UI等功能,功能着实强大!
本文主要是针对iOS 10的消息通知做介绍,所以很多代码没有对iOS 10之前做添加适配。
iOS推送分为Local Notifications(本地推送) 和 Remote Notifications(远程推送)(原理图来源于网络,如有侵权请告知,我会添加来源,我怕我赔不起)
Local Notifications(本地推送)
Local Notifications.png
App本地创建通知,加入到系统的Schedule里,如果触发器条件达成时会推送相应的消息内容
Remote Notifications(远程推送)
Remote Notifications1.jpg
图中,Provider是指某个iPhone软件的Push服务器,这篇文章我将使用我花了12块大洋(心疼)买的
APNS Pusher 作为我的推送源。
APNS 是Apple Push Notification Service(Apple Push服务器)的缩写,是苹果的服务器。
上图可以分为三个阶段:
第一阶段:APNS Pusher应用程序把要发送的消息、目的iPhone的标识打包,发给APNS。
第二阶段:APNS在自身的已注册Push服务的iPhone列表中,查找有相应标识的iPhone,并把消息发到iPhone。
第三阶段:iPhone把发来的消息传递给相应的应用程序, 并且按照设定弹出Push通知。
Remote Notifications2.jpeg
从上图我们可以看到:
首先是应用程序注册消息推送。
IOS跟APNS Server要deviceToken。应用程序接受deviceToken。
应用程序将deviceToken发送给PUSH服务端程序。
服务端程序向APNS服务发送消息。
APNS服务将消息发送给iPhone应用程序。
基本配置和基本方法
如果只是简单的本地推送,跳过1 2 步骤,直接到3
1、 如果你的App有远端推送的话,那你需要开发者账号的,需要新建一个对应你bundle的push 证书。证书这一块我就不说了,如果针对证书有什么问题可以给我留言,我会单独把证书相关的知识点整理起来!当然本人是非常喜欢的分享的(又装逼),如果你没有账号,我可以把我测试用的证书发给你,用于你的测试和学习,私聊我。
2、 Capabilities中打开Push Notifications 开关
在XCode7中这里的开关不打开,推送也是可以正常使用的,但是在XCode8中,这里的开关必须要打开,不然会报错:
Error Domain=NSCocoaErrorDomain Code=3000 &未找到应用程序的“aps-environment”的授权字符串& UserInfo={NSLocalizedDescription=未找到应用程序的“aps-environment”的授权字符串}
打开后会自动在项目里生成entitlements文件。
Push Notification开关.png
entitlements文件.png
3、 推送的注册
第一步: 导入 #import &UserNotifications/UserNotifications.h&
且要遵守&UNUserNotificationCenterDelegate&的协议,在Appdelegate.m中。
这里需要注意,我们最好写成这种形式(防止低版本找不到头文件出现问题)
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import &UserNotifications/UserNotifications.h&
第二步:我们需要在
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions中注册通知,代码如下
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self replyPushNotificationAuthorization:application];
return YES;
#pragma mark - 申请通知权限
- (void)replyPushNotificationAuthorization:(UIApplication *)application{
if (IOS10_OR_LATER) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error && granted) {
NSLog(@&注册成功&);
NSLog(@&注册失败&);
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
NSLog(@&========%@&,settings);
}else if (IOS8_OR_LATER){
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
[application registerUserNotificationSettings:settings];
[application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
[application registerForRemoteNotifications];
上面需要注意:
1. 必须写代理,不然无法监听通知的接收与点击事件
center.delegate =
下面是我在项目里定义的宏
#define IOS10_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] &= 10.0)
#define IOS9_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] &= 9.0)
#define IOS8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] &= 8.0)
#define IOS7_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] &= 7.0)
2. 之前注册推送服务,用户点击了同意还是不同意,以及用户之后又做了怎样的更改我们都无从得知,现在 apple 开放了这个 API,我们可以直接获取到用户的设定信息了。注意UNNotificationSettings是只读对象哦,不能直接修改!只能通过以下方式获取
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
NSLog(@&========%@&,settings);
打印信息如下:
========&UNNotificationSettings: 0x; authorizationStatus: Authorized, notificationCenterSetting: Enabled, soundSetting: Enabled, badgeSetting: Enabled, lockScreenSetting: Enabled, alertSetting: NotSupported, carPlaySetting: Enabled, alertStyle: Banner&
4、 远端推送需要获取设备的Device Token的方法是没有变的,代码如下
mark - 获取device Token
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
NSString *deviceString = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@&&&&]];
deviceString = [deviceString stringByReplacingOccurrencesOfString:@& & withString:@&&];
NSLog(@&deviceToken===========%@&,deviceString);
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
NSLog(@&[DeviceToken Error]:%@\n&,error.description);
5、这一步吊了,这是iOS 10系统更新时,苹果给了我们2个代理方法来处理通知的接收和点击事件,这两个方法在&UNUserNotificationCenterDelegate&的协议中,大家可以查看下。
@protocol UNUserNotificationCenterDelegate &NSObject&
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler __IOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0) __TVOS_PROHIBITED;
此外,苹果把本地通知跟远程通知合二为一。区分本地通知跟远程通知的类是UNPushNotificationTrigger.h类中,UNPushNotificationTrigger的类型是新增加的,通过它,我们可以得到一些通知的触发条件 ,解释如下:
UNPushNotificationTrigger (远程通知) 远程推送的通知类型UNTimeIntervalNotificationTrigger (本地通知) 一定时间之后,重复或者不重复推送通知。我们可以设置timeInterval(时间间隔)和repeats(是否重复)。UNCalendarNotificationTrigger(本地通知) 一定日期之后,重复或者不重复推送通知 例如,你每天8点推送一个通知,只要dateComponents为8,如果你想每天8点都推送这个通知,只要repeats为YES就可以了。UNLocationNotificationTrigger (本地通知)地理位置的一种通知,
当用户进入或离开一个地理区域来通知。
现在先提出来,后面我会一一代码演示出每种用法。还是回到两个很吊的代理方法吧
#pragma mark - iOS10 收到通知(本地和远端) UNUserNotificationCenterDelegate
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
UNNotificationRequest *request = notification.request;
UNNotificationContent *content = request.content;
NSDictionary *userInfo = content.userInfo;
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 收到远程通知:%@&,userInfo);
NSLog(@&iOS10 收到本地通知:{\\\\nbody:%@,\\\\ntitle:%@,\\\\nsubtitle:%@,\\\\nbadge:%@,\\\\nsound:%@,\\\\nuserInfo:%@\\\\n}&,body,title,subtitle,badge,sound,userInfo);
completionHandler(UNNotificationPresentationOptionBadge|
UNNotificationPresentationOptionSound|
UNNotificationPresentationOptionAlert);
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
UNNotificationRequest *request = response.notification.request;
UNNotificationContent *content = request.content;
NSDictionary *userInfo = content.userInfo;
NSNumber *badge = content.badge;
NSString *body = content.body;
UNNotificationSound *sound = content.sound;
NSString *subtitle = content.subtitle;
NSString *title = content.title;
if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
NSLog(@&iOS10 收到远程通知:%@&,userInfo);
NSLog(@&iOS10 收到本地通知:{\\\\nbody:%@,\\\\ntitle:%@,\\\\nsubtitle:%@,\\\\nbadge:%@,\\\\nsound:%@,\\\\nuserInfo:%@\\\\n}&,body,title,subtitle,badge,sound,userInfo);
completionHandler();
需要注意的:
1.下面这个代理方法,只会是app处于前台状态 前台状态 and 前台状态下才会走,后台模式下是不会走这里的
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
2.下面这个代理方法,只会是用户点击消息才会触发,如果使用户长按(3DTouch)、Action等并不会触发。
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
3.点击代理最后需要执行:completionHandler();
不然会报:
2016-09-27 14:42:16.353978 UserNotificationsDemo[1765:800117] Warning: UNUserNotificationCenter delegate received call to -userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: but the completion handler was never called.
4.不管前台后台状态下。推送消息的横幅都可以展示出来!后台状态不用说,前台时需要在前台代理方法中设置 ,设置如下:
completionHandler(UNNotificationPresentationOptionBadge|
UNNotificationPresentationOptionSound|
UNNotificationPresentationOptionAlert);
6、 iOS 10之前接收通知的兼容方法
#pragma mark -iOS 10之前收到通知
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(@&iOS6及以下系统,收到通知:%@&, userInfo);
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
NSLog(@&iOS7及以上系统,收到通知:%@&, userInfo);
completionHandler(UIBackgroundFetchResultNewData);
段结:是不是以为就结束了?NO NO NO(你以为离开了幻境,其实才刚刚踏入幻境!)上面的介绍了基本原理、基本配置以及基本方法说明,现在做完这些工作,我们的学习才刚刚开始!现在天时、地利、人和、可以开始下面推送coding的学习和测试了。
在用户日常生活中会有很多种情形需要通知,比如:新闻提醒、定时吃药、定期体检、到达某个地方提醒用户等等,这些功能在 UserNotifications 中都提供了相应的接口。
图片来源于网络.jpeg
我们先学会基本的技能简单的推送(爬),后面在学习进阶定制推送(走),最后看看能不能高级推送(飞不飞起来看个人了,我是飞不起来):
基本Local Notifications(本地推送) 和 Remote Notifications(远程推送)
一、 基本的本地推送
本地推送生成主要流程就是:
1. 创建一个触发器(trigger)
2. 创建推送的内容(UNMutableNotificationContent)
3. 创建推送请求(UNNotificationRequest)
4. 推送请求添加到推送管理中心(UNUserNotificationCenter)中
1、新功能trigger可以在特定条件触发,有三类:UNTimeIntervalNotificationTrigger、UNCalendarNotificationTrigger、UNLocationNotificationTrigger
1.1、 UNTimeIntervalNotificationTrigger:一段时间后触发(定时推送)
UNTimeIntervalNotificationTrigger *trigger1 = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:50 repeats:NO];
1.2 UNCalendarNotificationTrigger :调用
+ (instancetype)triggerWithDateMatchingComponents:(NSDateComponents *)dateComponents repeats:(BOOL)进行注册;时间点信息用 NSDateComponents.(定期推送)
NSDateComponents *components = [[NSDateComponents alloc] init];
components.weekday = 2;
components.hour = 16;
components.minute = 3;
UNCalendarNotificationTrigger *calendarTrigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];
1.3、UNLocationNotificationTrigger:调用
+ (instancetype)triggerWithRegion:(CLRegion *)region repeats:(BOOL)
进行注册,地区信息使用CLRegion的子类CLCircularRegion,可以配置region属性 notifyOnEntry和notifyOnExit,是在进入地区、从地区出来或者两者都要的时候进行通知,这个测试过程专门从公司跑到家时刻关注手机有推送嘛,果然是有的(定点推送)
CLLocationCoordinate2D center1 = CLLocationCoordinate2DMake(39.788857, 116.5559392);
CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:center1 radius:500 identifier:@&经海五路&];
region.notifyOnEntry = YES;
region.notifyOnExit = YES;
UNLocationNotificationTrigger *locationTrigger = [UNLocationNotificationTrigger triggerWithRegion:region repeats:YES];
2、创建推送的内容(UNMutableNotificationContent)
:属性readOnly
:属性有title、subtitle、body、badge、sound、lauchImageName、userInfo、attachments、categoryIdentifier、threadIdentifier
本地消息内容
内容限制大小
限制在一行,多出部分省略号
限制在一行,多出部分省略号
通知栏出现时,限制在两行,多出部分省略号;预览时,全部展示
注意点: body中printf风格的转义字符,比如说要包含%,需要写成%% 才会显示,\同样
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.title = @&Dely 时间提醒 - title&;
content.subtitle = [NSString stringWithFormat:@&Dely 装逼大会竞选时间提醒 - subtitle&];
content.body = @&Dely 装逼大会总决赛时间到,欢迎你参加总决赛!希望你一统X界 - body&;
content.badge = @666;
content.sound = [UNNotificationSound defaultSound];
content.userInfo = @{@&key1&:@&value1&,@&key2&:@&value2&};
3、创建完整的本地推送请求Demo
+ (void)createLocalizedUserNotification{
UNTimeIntervalNotificationTrigger *timeTrigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5.0f repeats:NO];
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.title = @&Dely 时间提醒 - title&;
content.subtitle = [NSString stringWithFormat:@&Dely 装逼大会竞选时间提醒 - subtitle&];
content.body = @&Dely 装逼大会总决赛时间到,欢迎你参加总决赛!希望你一统X界 - body&;
content.badge = @666;
content.sound = [UNNotificationSound defaultSound];
content.userInfo = @{@&key1&:@&value1&,@&key2&:@&value2&};
NSString *requestIdentifier = @&Dely.X.time&;
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifier content:content trigger:timeTrigger];
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (!error) {
NSLog(@&推送已添加成功 %@&, requestIdentifier);
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@&本地通知& message:@&成功添加推送& preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@&取消& style:UIAlertActionStyleCancel handler:nil];
[alert addAction:cancelAction];
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
运行结果如下:
装X决赛通知.jpg
二、 基本的远端推送
如果你想模拟远端推送,按照我前面介绍的配置基本环境、证书、push开关和基本方法就可以模拟远端的基本远端推送。
1、运行工程则会拿到设备的Device Token,后面会用到。
device token.png
2、现在我们需要一个推送服务器给APNS发送信息。我前面说了我花了12块大洋(心疼死我了)买了一个APNS pusher 来模拟远端推送服务,当然你可以不花钱也可以用到,例如:
APNS pusher
3、你需要把你刚刚获取的device token填到相应位置,同时你要配置好push证书哦。
4、需要添加aps内容了,然后点击send就OK了
&alert& : {
&title& : &iOS远程消息,我是主标题!-title&,
&subtitle& : &iOS远程消息,我是主标题!-Subtitle&,
&body& : &Dely,why am i so handsome -body&
&badge& : &2&
5、稍纵即逝你就收到了远端消息了
远端消息.jpg
6、Notification Management
对推送进行查、改、删。都需要一个必需的参数requestIdentifier
1、更新通知
Local Notification需要通过更新request.相同的requestIdentifier,重新添加到推送center就可以了,说白了就是重新创建local Notification request(只要保证requestIdentifier就ok了),应用场景如图
Local Notification更新前.png
Local Notification更新后.png
Remote Notification 更新需要通过新的字段apps-collapse-id来作为唯一标示,我前面用的APNS pusher暂不支持这个字段,不过github上有很多这样的工具:
这样remote 也可以更新推送消息
2、推送消息的查找和删除
- (void)getPendingNotificationRequestsWithCompletionHandler:(void(^)(NSArray&UNNotificationRequest *& *requests))completionH
- (void)removePendingNotificationRequestsWithIdentifiers:(NSArray&NSString *& *)
- (void)removeAllPendingNotificationR
- (void)getDeliveredNotificationsWithCompletionHandler:(void(^)(NSArray&UNNotification *& *notifications))completionHandler __TVOS_PROHIBITED;
- (void)removeDeliveredNotificationsWithIdentifiers:(NSArray&NSString *& *)identifiers __TVOS_PROHIBITED;
- (void)removeAllDeliveredNotifications __TVOS_PROHIBITED;
测试如下:
(void)notificationAction{
NSString *requestIdentifier = @&Dely.X.time&;
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
[center getDeliveredNotificationsWithCompletionHandler:^(NSArray&UNNotification *& * _Nonnull notifications) {
段结: 收到通知时你需要在appdelegate里面的代理方法里处理你的需求逻辑,这个需要你自己写了。到目前为止你掌握了基本的本地推送和基本的远端推送!
不知不觉写了这么多字(全是TM废话)、本来继续打算写进阶的本地和远端推送(Media Attachments、Notification Actions、自定义推送界面等),留着下一篇博客继续分享吧,欲知后事如何,且听下会装X!
如果你喜欢可以点个喜欢^_^(竟有如此厚颜无耻之人)
下集预告:
推送图片.jpg
推送图片2.jpg
参考资料:
文/Dely(简书作者)
原文链接:/p/c58f
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:12942次
排名:千里之外
原创:75篇
转载:61篇
(7)(1)(1)(1)(2)(98)(27)> 消息推送 > 消息推送IOS文档 > iOS集成文档v1.4.0
 介绍
友盟消息推送组件帮助您实时的推送消息给用户。
版本号:v1.4.0
查看老版本的文档可以
遇到问题可以查看论坛帖子,绝大多数问题都可以在论坛找到:
基本功能集成指南
高级功能集成指南
测试与调试
下载的压缩包中将包括以下内容:
UMessage_Sdk_Introductions.html
该文件介绍如何使用友盟消息推送SDK
UMessage_Sdk_ReleaseNotes.html
该文件记录了友盟消息推送SDK的更新日志
UMessage_Sdk_Api_Reference/
该文件夹中包含了友盟消息推送的API文档
UMessage_Sdk_x.x.x/
该文件夹中包含了SDK的库文件
UMessage_Sdk_Demo/
该文件夹中包含了示例工程
NotificatonService/
iOS10的Notificaton Service
集成之前, 请在申请开通友盟消息推送服务。
 基本功能集成指南
请先在友盟的消息推送管理后台中创建App,获得AppKey和AppSecret
UMessage_Sdk_All_x.x.x.zip并解压缩
所需SDK文件夹:UMessage_Sdk_x.x.x
请在你的工程目录结构中,右键选择Add-&Existing Files…,选择这个文件夹。或者将这个文件夹拖入XCode工程目录结构中,在弹出的界面中勾选Copy items into destination group's folder(if needed), 并确保Add To Targets勾选相应的target。
引入库文件
增加UserNotification.framework到项目中。具体操作如下:点击项目----&TARGET----&Build Phases----&Link Binary with Libraries ----&左侧+号----&搜索UserNotification
配置(可选)
SDK采用ARC管理内存,非ARC项目也是默认支持,如遇问题,请联系我们
如果您使用了-all_load,可能需要添加libz的库:
TARGETS--&Build Phases--&Link Binary With Libraries--& + --&libz.dylib
SDK支持iOS 6.0+
打开推送开关
点击项目----&TARGET----&Capabilities,将这里的Push Notification的开关打开,效果如图所示:
注意:一定要打开Push Notification,且两个steps都是正确的,否则会报如下错误:Code=3000 "未找到应用程序的“aps-environment”的授权字符串"
打开*AppDelegate.m,依次按照以下步骤集成:
引入UMessage.h,UserNotifications.h,UNUserNotificationCenterDelegate
didFinishLaunchingWithOptions中的设置:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
//初始化方法,也可以使用(void)startWithAppkey:(NSString *)appKey launchOptions:(NSDictionary * )launchOptions httpsenable:(BOOL)这个方法,方便设置https请求。
[UMessage startWithAppkey:@"your appkey" launchOptions:launchOptions];
//注册通知,如果要使用category的自定义策略,可以参考demo中的代码。
[UMessage registerForRemoteNotifications];
//iOS10必须加下面这段代码。
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate=
UNAuthorizationOptions types10=UNAuthorizationOptionBadge|
UNAuthorizationOptionAlert|UNAuthorizationOptionS
[center requestAuthorizationWithOptions:types10
completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) {
//点击允许
//这里可以添加一些自己的逻辑
//点击不允许
//这里可以添加一些自己的逻辑
//打开日志,方便调试
[UMessage setLogEnabled:YES];
didRegisterForRemoteNotificationsWithDeviceToken中设置(1.2.7开始可以不用设置)
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
// 1.2.7版本开始不需要用户再手动注册devicetoken,SDK会自动注册
//[UMessage registerDeviceToken:deviceToken];
//iOS10以下使用这个方法接收通知
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
//关闭友盟自带的弹出框
[UMessage setAutoAlert:NO];
[UMessage didReceiveRemoteNotification:userInfo];
self.userInfo = userI
//定制自定的的弹出框
if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"标题"
message:@"Test On ApplicationStateActive"
delegate:self
cancelButtonTitle:@"确定"
otherButtonTitles:nil];
[alertView show];
//iOS10新增:处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
NSDictionary * userInfo = notification.request.content.userI
if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//应用处于前台时的远程推送接受
//关闭友盟自带的弹出框
[UMessage setAutoAlert:NO];
//必须加这句代码
[UMessage didReceiveRemoteNotification:userInfo];
//应用处于前台时的本地推送接受
//当应用处于前台时提示设置,需要哪个可以设置哪一个
completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
//iOS10新增:处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
NSDictionary * userInfo = response.notification.request.content.userI
if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//应用处于后台时的远程推送接受
//必须加这句代码
[UMessage didReceiveRemoteNotification:userInfo];
//应用处于后台时的本地推送接受
如需关闭推送,请使用[UMessage unregisterForRemoteNotifications](iOS10此功能存在系统bug,建议不要在iOS10使用。iOS10出现的bug会导致关闭推送后无法打开推送。)
关于iOS如何在接收到推送后打开指定页面,可以看论坛帖子:
至此,消息推送基本功能的集成已经完成。
 高级功能集成指南
自定义推送显示按钮
推送消息被下拉、左划以及3D Touch设备的点击,可以执行预先设定好的操作,如确认、取消、快捷回复等。
如iOS10以下的系统效果下图所示:
如iOS10以上的系统分为3D Touch设备和非3D Touch设备,具体的效果如下所示。
非3D Touch
注意:使用此功能,设备的系统版本需在iOS8及以上。
编写策略代码
iOS10以前的UIUserNotificationAction相关属性
// 行为标识符,用于调用代理方法时识别是哪种行为。
@property (nonatomic, copy, readonly) NSString *
// 行为名称。
@property (nonatomic, copy, readonly) NSString *
// 即行为是否打开APP。
@property (nonatomic, assign, readonly) UIUserNotificationActivationMode activationM
// 是否需要解锁。
@property (nonatomic, assign, readonly, getter=isAuthenticationRequired) BOOL authenticationR
// 这个决定按钮显示颜色,YES的话按钮会是红色。
@property (nonatomic, assign, readonly, getter=isDestructive) BOOL
iOS10的UNNotificationAction相关属性
// The unique identifier for this action.
@property (NS_NONATOMIC_IOSONLY, copy, readonly) NSString *
// The title to display for this action.
@property (NS_NONATOMIC_IOSONLY, copy, readonly) NSString *
// The options configured for this action.
@property (NS_NONATOMIC_IOSONLY, readonly) UNNotificationActionO
调用U-Push的自定义注册方法
//iOS10以前注册category
NSSet *categories = [NSSet setWithObject:actionCategory1];
[UMessage registerForRemoteNotifications:categories];
//iOS10注册category
NSSet *categories_ios10 = [NSSet setWithObjects:category1_ios10, nil];
[center setNotificationCategories:categories_ios10];
添加并运行接收通知代码
//iOS10以前接收的方法
-(void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler
//这个方法用来做action点击的统计
[UMessage sendClickReportForRemoteNotification:userInfo];
//下面写identifier对各个交互式的按钮进行业务处理
//iOS10以后接收的方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
NSDictionary * userInfo = response.notification.request.content.userI
if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
[UMessage didReceiveRemoteNotification:userInfo];
if([response.actionIdentifier isEqualToString:@"*****你定义的action id****"])
//这个方法用来做action点击的统计
[UMessage sendClickReportForRemoteNotification:userInfo];
//应用处于后台时的本地推送接受
在U-Push后台添加推送策略
登录账号并进入后,将提醒方式下方的Category ID
设置为需要推送的策略的id,如下图所示:
示例:将标签“男”绑定至该设备:
[UMessage addTag:@"男"
response:^(id responseObject, NSInteger remain, NSError *error) {
//add your codes
小提示:tag参数既可以是NSString的单个tag,也可以是NSArray,NSSet的tag集合哦!
示例:将标签"男"从设备绑定中删除:
[UMessage removeTag:@"男"
response:^(id responseObject, NSInteger remain, NSError *error) {
//add your codes
小提示:tag参数既可以是NSString的单个tag,也可以是NSArray,NSSet的tag集合哦!
获取tag列表
示例: 获取tag列表
[UMessage getTags:^(NSSet *responseTags, NSInteger remain, NSError *error) {
//add your codes
重置tag列表
示例: 重置tag列表
[UMessage removeAllTags:^(id responseObject, NSInteger remain, NSError *error) {
可以为单个tag(NSString)也可以为tag集合(NSArray、NSSet)
每台设备最多绑定64个tag,超过64个,绑定tag不再成功
单个tag最大允许长度50字节,编码UTF-8,超过长度自动截取
当需要将设备标记为别名时,可用。
添加别名(addAlias)
示例: 将新浪微博的某用户绑定至设备,老的绑定的设备还在
[UMessage addAlias:@"" type:kUMessageAliasTypeSina response:^(id responseObject, NSError *error) {
type的类型已经默认枚举好平台类型,在UMessage.h最上侧,形如:kUMessageAliasTypeSina
type的类型如果默认的满足不了需求,可以自定义这个字段
设置别名(setAlias)
示例: 将新浪微博的某用户绑定至设备,覆盖老的,一一对应
[UMessage setAlias:@"" type:kUMessageAliasTypeSina response:^(id responseObject, NSError *error) {
删除别名(removeAlias)
示例: 将新浪微博的别名绑定删除
[UMessage removeAlias:@"" type:kUMessageAliasTypeSina response:^(id responseObject, NSError *error) {
设置地理位置信息
[UMessage setLocation:location];
设置是否允许SDK自动清空角标(默认开启)
[UMessage setBadgeClear:NO];
设置是否允许SDK当应用在前台运行收到Push时弹出Alert框(默认开启)
[UMessage setAutoAlert:NO];
设置当前 App 的发布渠道(默认"App Store")
[UMessage setChannel:@"App Store"]
自定义弹出框后,想补发前台的消息的点击统计
[UMessage sendClickReportForRemoteNotification:userInfo]
 测试与调试
 开启调试模式
打开调试日志
[UMessage setLogEnabled:YES];
 调试步骤
确认证书设置正确。参见 iOS 证书设置指南
确认Provisioning Profile配置正确,并已更新
在友盟消息推送后台上传正确的 Push 证书
启动应用程序,并在选择接受推送通知
确认 App 是开启 Push 权限的
在网站后台选择对应的Device Token进行推送测试
 如何获取设备的 DeviceToken
开发环境下:
方法1:在 didRegisterForRemoteNotificationsWithDeviceToken 中添加如下语句
NSLog(@"%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"&" withString: @""]
stringByReplacingOccurrencesOfString: @"&" withString: @""]
stringByReplacingOccurrencesOfString: @" " withString: @""]);
方法2:在 didFinishLaunchingWithOptions:(NSDictionary *)launchOptions中 开启UMessage的Log,然后寻找deviceToken的字段
[UMessage setLogEnabled:YES];
以上任一方式都可在控制台获取一个长度为64的测试设备的DeviceToken串
生产环境下,用户需要用抓包工具、代理工具等自行获取device_token
 集成帮助
一、IOS为什么获取不到设备的DeviceToken
二、IOS可以自定义App在前台接受到消息的弹出框么
三、为什么集成完SDK后,App运行没有弹出打开通知的对话框
四、为什么集成成功后iOS收不到推送通知
更多常见问题请点击访问:
如果还有问题,请把您的问题发邮件至或者联系官网底部云客服系统(在线时间:工作日10:00~18:00)。如需要了解更多信息,请申请加入消息推送官方QQ群:,(需提供友盟appkey),我们会尽快回复您。
如果可以附上相关日志,我们可以更好的帮助您解决问题,通过[UMessage setLogEnabled:YES];打开Debug模式,在logcat里查看log,发布应用时请去掉。

我要回帖

更多关于 screennotifications 的文章

 

随机推荐