iOS推送通知拓展NotificationServiceExtension实践

avatar

前言

自iOS10 更新以来,Apple 表示这是 iOS 有史以来最大的升级(our biggest release yet),更加智能开放的Siri、强化应用对3DTouch支持、 HomeKit 、电话拦截及全新设计的通知等等。html

iOS 10 中将以前繁杂的推送通知统一成UserNotifications.framework 来集中管理和使用通知功能,还增长一些实用的功能——撤回单条通知、更新已展现通知、中途修改通知内容、在通知中显示多媒体资源、自定义UI等功能。ios

iOS10推送通知的有如下两个两个扩展框架:git

  • UNNotificationServiceExtension(通知服务拓展)
  • UNNotificationContentExtension(通知内容拓展)
通知拓展 特性
UNNotificationServiceExtension 在收到通知后,展现通知前,作一些事情的。好比,增长附件,网络请求等。
UNNotificationContentExtension 能够经过提早配置的categoryIdentifier来定制推送显示的界面

1、UNNotificationServiceExtension - 通知服务扩展

1.什么是UNNotificationServiceExtension?

的主要功能,是让咱们在收到远程推送的时候,在推送展现以前对其进行修改,由于咱们收到远程推送以前会先去执行Service Extension中的代码,这样就能够在收到远程推送展现以前作一些操做。github

2.UNNotificationServiceExtension的做用

通知服务拓展能作什么?举个例子:bash

1.更改推送内容

经过远程推送,推送的内容的title="1",我能够在收到推送将要显示以前将标题修改为title="2",那么推送条展现的title就是2。网络

2.对推送内容加解密

在发送推送的时候发送一段用公钥加密的内容,而后设备收到推送以后,用私钥进行解密而后再去展现。例如开发者不想让第三方推送sdk(极光推送等)知晓推送内容,则能够采用通知服务拓展。框架

3.推送事件响应

在推送发送时,可使用服务拓展对通知的状态(例如到达率)作统计。工具

4.富媒体下载

当远程推送须要展现多媒体的时候,也须要在这下载,下载完毕以后,获取本地下载文件路径再进行展现。对下载附件多媒体得须要Service Extension。测试

3.UNNotificationServiceExtension实践

3.1 建立一个Service Extension

File -> New -> Target
选择拓展 ui

avatar
随后点击建立拓展便可,发现此时在项目中出现“xxxServiceExtension”的文件夹。
文件夹中包含了推送拓展类NotificationService。
avatar

3.2 测试

第一步,选择target为extension,运行项目:

第二步,选择当前项目

第三步,在NotificationService.m中的didReceiveNotificationRequest中添加断点:

第四步,发个远程推送,注意,本地推送是没反应的。

注意

新加 NotificationServiceExtension的项目,对应的的Extension target的Build Phases-》link binary with libraries 加上

  • libresolv.tbd
  • libz.tbd

3.2 远程推送相关注意事项

相对于普通推送,推送服务拓展payload的内容基本相同,举个例子:

{
  "aps":{
    "alert":{
      "title":"iOS 10 title",
      "subtitle":"iOS 10 subtitle",
      "body":"iOS 10 body"
    },
    "mutable-content":1,
    "category":"saySomethingCategory",
    "sound":"default",
    "badge":3
  }
}
复制代码

注意,推送内容多了一个mutable-content,它表示咱们会在接收到通知时对内容进行更改。
开发者在didReceiveNotificationRequest方法中有30秒的时间对推送内容到达前进行处理。例如:

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    
    // Modify the notification content here...
    self.bestAttemptContent.title = [NSString stringWithFormat:@"%@ [modified]", self.bestAttemptContent.title];
    self.bestAttemptContent.body = @"我是新修改的body";
    self.bestAttemptContent.title = @"我是新修改的title";
    self.bestAttemptContent.subtitle = @"我是新修改的subtitle";
    
    self.contentHandler(self.bestAttemptContent);
}
复制代码

3.3 推送测试工具

这里推荐Knuff: github.com/KnuffApp/Kn…

参考文献http://www.cocoachina.com/ios/20160628/16833.html

极光接入

若开发者使用极光推送,则下载极光的SDK ,把里面的lib文件拷贝到工程中:

相关文章
相关标签/搜索