参考自Fancy Pixel
本例Demo在这里下载
iOS8开放了可操作通知消息的功能,但是还是不支持在通知的消息中文字输入功能。现在iOS9这个API已经开放了。接下来就简单介绍一下。以本地通知为例。
Category 与 Actions
- Category( UIUserNotificationCategory,
UIMutableUserNotificationCategory)
对一个通知来说,可能有一系列的Actions组成(最小0个,最大4个),需要把这些Actions关联到一个Category里,Category在注册通知时使用,发送该通知时需要把关联到这个Category。这样,当出发一个通知时,就会显示预设好的Actions。
Category分为两类,Default 和 Minimal,Default最多支持4个Action,Minimal则最多支持2个。Default用于标准弹框通知显示Action列表,Minimal用于锁屏、通知中心、顶部通知(banner)时显示 Actions列表。
经过测试发现,如果Default 的actions这是为nil,则推送标准弹框的Actions列表,只显示默认的 “打开” 按钮。
显示的Actions顺序,从右往左,为添加到 Category里的顺序。示例代码:
UIMutableUserNotificationCategory *category = [[UIMutableUserNotificationCategory alloc]init];
category.identifier = @"category_id";
//[category setActions:@[textAction] forContext:UIUserNotificationActionContextDefault];
[category setActions:@[textAction,textActionFast] forContext:UIUserNotificationActionContextMinimal];
NSSet *categories = [NSSet setWithObjects:category, nil];
- Action( UIUserNotificationAction,UIMutableUserNotificationAction)
iOS8以后,支持额外的自定义Actions。锁屏界面、顶部通知栏(banner)、通知中心 支持最多两个Action;标准弹框通知,支持最多四个Action。如果有多以的Action则会被抛弃。iOS9加入了Text Inout的功能。示例代码:
UIMutableUserNotificationAction *textAction = [[UIMutableUserNotificationAction alloc] init];
textAction.identifier = @"test_text_action";
textAction.title = @"回复";
textAction.activationMode = UIUserNotificationActivationModeForeground;
textAction.authenticationRequired = YES;
textAction.behavior = UIUserNotificationActionBehaviorTextInput;
UIMutableUserNotificationAction *actionFast = [[UIMutableUserNotificationAction alloc] init];
textActionFast.identifier = @"test_text_action1";
textActionFast.title = @"快速回复";
textActionFast.activationMode = UIUserNotificationActionContextDefault;
textActionFast.authenticationRequired = NO;
textActionFast.behavior = UIUserNotificationActionBehaviorDefault;
- 响应Action
本地通知
对于本地通知,对应的回调有两个:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification NS_AVAILABLE_IOS(4_0);
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void(^)())completionHandler NS_AVAILABLE_IOS(8_0);
点击某个Action的时候,会响应 handleActionWithIdentifier 回调,,identifier 是某个Action的标示,根据该标示找到对应的Action,需要注意的是,该回调在处理完,需要调用 completionHandler 。
如果用户是直接点击的通知,或者点击的 “打开” 即通知的默认操作,则会调用 didReceiveLocalNotification 回调。
最终结果图: