惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 三生石上(FineUI控件)
S
SegmentFault 最新的问题
阮一峰的网络日志
阮一峰的网络日志
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
雷峰网
雷峰网
Apple Machine Learning Research
Apple Machine Learning Research
WordPress大学
WordPress大学
博客园 - 司徒正美
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
宝玉的分享
宝玉的分享
爱范儿
爱范儿
月光博客
月光博客
The GitHub Blog
The GitHub Blog
M
MIT News - Artificial intelligence
H
Hackread – Cybersecurity News, Data Breaches, AI and More
B
Blog
T
Tailwind CSS Blog
美团技术团队
D
Docker
V
Visual Studio Blog
Martin Fowler
Martin Fowler
博客园 - 聂微东
The Cloudflare Blog

博客园 - 幽谷清水

ABP .Net Core Entity Framework迁移使用MySql数据库 理解OAuth 2.0 IdentityServer4 中文文档 【转】ASP.NET Core 依赖注入 asp.net core部署到iis中出现 HTTP Error 502.5 - Process Failure的问题 在IIS上部署你的ASP.NET Core 2.1项目 AppBoxPro(权限管理框架--FineUIPro基础版+工厂模式+ADO.NET+存储过程) 阿里云 Windows Server 2012 r2 部署asp.net mvc网站 平坑之旅 tfs 禁止多人签出 Sql Server 向上取整、向下取整、四舍五入取整 微信WeixinJSBridge API Memcached+WebApi记录 支付宝友盟编译报错 控制器隐藏了导航 下页pop 导航位置看到黑条 安装Cocoapods xcode 插件 3.1 - Apps or metadata that mentions the name of any other mobile platform will be rejected 苹果电话、加急 火狐浏览器sqlite插件
iOS8自定义推送显示按钮及推送优化
幽谷清水 · 2016-05-17 · via 博客园 - 幽谷清水
导语

在iOS8中,推送消息不再只是简单地点击打开客户端,对推送消息下拉时还可以执行预先设定好的操作,接下来我们来介绍如何自定义推送信息显示按钮和对推送的一些优化策略。

注册推送

在iOS8中,我们使用新的函数来注册通知,如下:

- (void)registerForRemoteNotifications NS_AVAILABLE_IOS(8_0)

该函数的作用是向苹果服务器注册该设备,注册成功过后会回调

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken NS_AVAILABLE_IOS(3_0);

注册失败则回调

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error NS_AVAILABLE_IOS(3_0);

执行registerForRemoteNotifications只是完成了与APNS的注册交互,接下来还要设置推送的类型和策略。如果没有设置则接收到的消息都是以静默的方式接收。

设置推送类型

- (void)registerUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings NS_AVAILABLE_IOS(8_0);

在这里我们用到了UIUserNotificationSettings这个新类,苹果对其解释是这样的。

A UIUserNotificationSettings object encapsulates the types of notifications that can be displayed to the user by your app. Apps that use visible or audible alerts in conjunction with a local or push notification must register the types of alerts they employ. UIKit correlates the information you provide with the user’s preferences to determine what types of alerts your app is allowed to employ.

简单来说就是我们可以自行注册推送的提醒类型。再来看看UIUserNotificationSettings为我们提供了那些函数。查看API,我们只找到了

+ (instancetype)settingsForTypes:(UIUserNotificationType)types
                  categories:(NSSet *)categories;

UIUserNotificationType就是以往我们设定的推送声音、推送数量Badge和是否Alter的参数组合。因为它们是NS_OPTIONS类型,所以是可以多选的。

我们重点放在categories上。可以看到,categories的类型是一个集合(NSSet *),也就是说我们可以设置多个推送策略。继续查找API,我们找到了UIUserNotificationCategory。苹果的说明是这样的

A UIUserNotificationCategory object encapsulates information about custom actions that your app can perform in response to a local or push notification. Each instance of this class represents a group of actions to display in conjunction with a single notification. The title of each action is uses as the title of a button in the alert displayed to the user. When the user taps a button, the system reports the selected action to your app delegate.

就是说我们对每一条推送信息可以设置一组行为,行为以按钮方式显示。当我们点击按钮时会调用app delegate的代理方法。
查看UIUserNotificationCategory相关属性

@property (nonatomic, copy, readonly) NSString *identifier;
  • identifier:策略标识,在推送时用来决定客户端显示哪种推送策略,稍后会介绍。

看到该属性是只读的,我们在自定义策略时使用的是UIMutableUserNotificationCategory来设置,设置方法如下:

- (void)setActions:(NSArray *)actions forContext:(UIUserNotificationActionContext)context;

对一个策略我们可以设置多个行为,使用的是UIUserNotificationAction。

查看UIUserNotificationAction相关属性

// The unique identifier for this action.
@property (nonatomic, copy, readonly) NSString *identifier;
  • identifier:行为标识符,用于调用代理方法时识别是哪种行为。
  • title:行为名称。
  • UIUserNotificationActivationMode:即行为是否打开APP。
  • authenticationRequired:是否需要解锁。
  • destructive:这个决定按钮显示颜色,YES的话按钮会是红色。

同样由于这些属性都是只读的,我们使用UIMutableUserNotificationAction来生成自定义行为。

编码

我们设置两种推送策略,每种策略分别设置两种行为。代码如下:

if(8.0 <= [UIDevice currentDevice].systemVersion.doubleValue)
{
    [[UIApplication sharedApplication] registerForRemoteNotifications];

    UIMutableUserNotificationAction * action1 = [[UIMutableUserNotificationAction alloc] init];
    action1.identifier = @"action1";
    action1.title=@"策略1行为1";
    action1.activationMode = UIUserNotificationActivationModeForeground;
    action1.destructive = YES;

    UIMutableUserNotificationAction * action2 = [[UIMutableUserNotificationAction alloc] init];
    action2.identifier = @"action2";
    action2.title=@"策略1行为2";
    action2.activationMode = UIUserNotificationActivationModeBackground;
    action2.authenticationRequired = NO;
    action2.destructive = NO;

    UIMutableUserNotificationCategory * category1 = [[UIMutableUserNotificationCategory alloc] init];
    category1.identifier = @"Category1";
    [category1 setActions:@[action2,action1] forContext:(UIUserNotificationActionContextDefault)];

    UIMutableUserNotificationAction * action3 = [[UIMutableUserNotificationAction alloc] init];
    action3.identifier = @"action3";
    action3.title=@"策略2行为1";
    action3.activationMode = UIUserNotificationActivationModeForeground;
    action3.destructive = YES;

    UIMutableUserNotificationAction * action4 = [[UIMutableUserNotificationAction alloc] init];
    action4.identifier = @"action4";
    action4.title=@"策略2行为2";
    action4.activationMode = UIUserNotificationActivationModeBackground;
    action4.authenticationRequired = NO;
    action4.destructive = NO;

    UIMutableUserNotificationCategory * category2 = [[UIMutableUserNotificationCategory alloc] init];
    category2.identifier = @"Category2";
    [category2 setActions:@[action4,action3] forContext:(UIUserNotificationActionContextDefault)];

    UIUserNotificationSettings *uns = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound) categories:[NSSet setWithObjects: category1,category2, nil]];

    [[UIApplication sharedApplication] registerUserNotificationSettings: uns];
}

关于推送证书制作请百度,这里推荐一个推送测试工具

  • 推送策略一
      {
          "aps":{
          "alert":"推送内容",
          "sound":"default",
          "badge":0,
          "category":"Category1"
          }
      }
    显示结果:

    策略一

  • 推送策略二
      {
          "aps":{
          "alert":"推送内容",
          "sound":"default",
          "badge":0,
          "category":"Category2"
          }
      }
    显示结果:

    策略二

点击相应按钮会激活代理方法

- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler NS_AVAILABLE_IOS(8_0);

这里我们根据传过来的identifier确定点击了哪个按钮,并执行相应操作。

推送优化

苹果APNS对推送内容大小限制不能超过256个字节(现在这个限制好像放宽了)。如果推送消息内容过多,不仅会造成推送延迟,还会消耗流量。对于推送信息中重复的文本内容,我们可以在本地字符串strings中自定义键值动态设定参数来完成推送。

Localizable.strings中添加:

"pushkey" = "%@ 的iOS8自定义推送显示按钮及推送优化教程 %@是一名iOS开发者,正在前行。";

设置推送信息

{
     "aps":{
        "alert":{"loc-args":["Arms","Arms"],"loc-key":"pushkey"},
        "sound":"default",
        "badge":0,
        "category":"Category2"
    }
}

显示结果:

本地字符串推送