IOS 10 新特性以及介绍-Notifications

<pre>上一篇中讲到Message中的一些特性,本次主要讲下Notification的特性</pre>

iOS10相对于之前的版本,主要是开发者可以使用Extension的形式修改和展示内容,主要是<code>UNNotificationServiceExtension</code>和<code>UNNotificationContentExtension</code>。同时也添加了其他方面的支持,例如<code>UNNotificationTrigger</code>、<code>UNNotificationAttachment</code>、<code>UNNotificationAction</code>。本次讲的主要有以下几点:

  • UNNotificationTrigger(通知触发条件设定)
  • UNNotificationAttachment (通知附件)
  • UNNotificationContentExtension (通知内容扩展)
  • UNNotificationServiceExtension (通知服务扩展)
  • UNNotificationAction (通知响应事件)

1、UNNotificationTrigger(通知触发条件设定)

主要是针对本地通知触发时机的设置,可以使用下面方式设置:

  1. UNPushNotificationTrigger:这个是苹果通知服务的 Trigger,对外没有暴露任何接口属性,不需要开发者创建,由系统创建。
  2. UNTimeIntervalNotificationTrigger(时间触发器):通过初始化方法设置通知的timeInterval(触发间隔)
    和repeats(是否重复触发),若 repeats 设置为 false,通知将在 timeInterval 之后被推送。
  3. UNCalendarNotificationTrigger(日期触发器):类似 UNTimeIntervalNotificationTrigger,也是时间触发器,只不过初始化时第一个参数为 DateComponents类型,可设置具体的触发时间比如8:00 AM等,也可设置是否重复触发。
  4. UNLocationNotificationTrigger(位置触发器):通过设置 CLRegion类型参数设置位置信息,当用户处于某一区域时,自动推送通知。

使用:

  //设置Notification内容
  UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
  content.title = [NSString localizedUserNotificationStringForKey:@"title!" arguments:nil];
  content.body = [NSString localizedUserNotificationStringForKey:@"body" arguments:nil];
  content.subtitle = [NSString localizedUserNotificationStringForKey:@"subtitle" arguments:nil];
  content.sound = [UNNotificationSound defaultSound];
  
  //初始化时间触发器
  UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];
  UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"Identifier"
                                                                        content:content
                                                                        trigger:trigger];
  
  // 请求计划推送
  [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
      if(error)
      {
          NSLog(@"%@",error);
      }
  }];

2、UNNotificationAttachment(通知附件)

苹果所支持的推送附件类型包含视频,音频,图片,苹果的文档中对文件的类型和大小做了如下限制:传送门
使用说明:

  • 本地通知:

设置<code>UNMutableNotificationContent</code>如下属性

@property (NS_NONATOMIC_IOSONLY, copy) NSArray <UNNotificationAttachment *> *attachments```

  • 远程通知:

通过URL地址下载资源,然后将资源设置到request.content.attachments

示例代码:

- (void)handlerImageWith:(NSString *)attachUrl{
   
   [self downloadFileAndSave:[NSURL URLWithString:attachUrl] handler:^(NSURL *localUrl) {
       if (localUrl){
           UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:@"image_download" URL:localUrl options:nil error:nil];
           self.bestAttemptContent.attachments = @[attachment];
       }
       self.contentHandler(self.bestAttemptContent);
   }];

}

- (void)downloadFileAndSave:(NSURL *)url handler:(void (^)(NSURL *))handler{
   NSURLSession *session = [NSURLSession sharedSession];
   
   NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url
                                                       completionHandler:^(NSURL * _Nullable location,
                                                                           NSURLResponse * _Nullable response,
                                                                           NSError * _Nullable error) {
                                                           NSURL *localURL = nil;
                                                           if(!error){
                                                               NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                                                               // response.suggestedFilename : 建议使用的文件名,一般跟服务器端的文件名一致
                                                               NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];
                                                               
                                                               // 将临时文件剪切或者复制Caches文件夹
                                                               NSFileManager *mgr = [NSFileManager defaultManager];
                                                               
                                                               // AtPath : 剪切前的文件路径
                                                               // ToPath : 剪切后的文件路径
                                                               [mgr moveItemAtPath:location.path toPath:file error:nil];
                                                               
                                                               if (file && ![file  isEqualToString: @""])
                                                               {
                                                                   localURL = [NSURL URLWithString:[@"file://" stringByAppendingString:file]];
                                                               }
                                                           }
                                                           handler(localURL);
                                                       }];
   [downloadTask resume];
} 

注意事项:

  • UNNotificationContent 的 attachments虽然是一个数组,但是系统只会展示第一个 attachment 对象的内容。不过你依然可以发送多个 attachments,然后在要展示的时候再重新安排它们的顺序,以显示最符合情景的图片或者视频。另外,你也可能会在自定义通知展示 UI 时用到多个 attachment。
  • 在当前 beta (iOS 10 beta 4) 中,serviceExtensionTimeWillExpire被调用之前,你有 30 秒时间来处理和更改通知内容。对于一般的图片来说,这个时间是足够的。但是如果你推送的是体积较大的视频内容,用户又恰巧处在糟糕的网络环境的话,很有可能无法及时下载完成。
  • 如果你想在远程推送来的通知中显示应用 bundle 内的资源的话,要注意 extension 的 bundle 和 app main bundle 并不是一回事儿。你可以选择将图片资源放到 extension bundle 中,也可以选择放在 main bundle 里。总之,你需要保证能够获取到正确的,并且你具有读取权限的 url。关于从 extension 中访问 main bundle,可以参看这篇回答
  • 系统在创建 attachement 时会根据提供的 url 后缀确定文件类型,如果没有后缀,或者后缀无法不正确的话,你可以在创建时通过 UNNotificationAttachmentOptionsTypeHintKey
    指定资源类型
  • 如果使用的图片和视频文件不在你的 bundle 内部,它们将被移动到系统的负责通知的文件夹下,然后在当通知被移除后删除。如果媒体文件在 bundle 内部,它们将被复制到通知文件夹下。每个应用能使用的媒体文件的文件大小总和是有限制,超过限制后创建 attachment 时将抛出异常。可能的所有错误可以在 UNError中找到。
  • 你可以访问一个已经创建的 attachment 的内容,但是要注意权限问题。可以使用 startAccessingSecurityScopedResource来暂时获取以创建的 attachment 的访问权限。比如:
if(notification.request.content.attachments && notification.request.content.attachments.count > 0){
        NSURL *imageUrl = notification.request.content.attachments[0].URL;
        if([imageUrl startAccessingSecurityScopedResource]){
            NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
            UIImage *image = [[UIImage alloc] initWithData:imageData];
            self.imageView.image = image;
            [imageUrl stopAccessingSecurityScopedResource];
        }
    }

3、UNNotificationContentExtension(通知内容扩展)

通知内容扩展需要新建一个 UNNotificationContentExtension Target,之后只需在 viewcontroller 的中实现相应的接口,即可以对 app 的通知页面进行自定义扩展,扩展主要用于自定义 UI。扩展页面样式可以在 plist 中配置,字段说明如下:

  • UNNotificationExtensionCategory: 要让通知支持内容扩展,需要将通知的 categoryIdentifier(类型标示) 加入此处。
  • UNNotificationExtensionDefaultContentHidden: 默认内容隐藏,如果设为 YES,则最下面通知 content 部分会隐藏。
  • UNNotificationExtensionIntialContentSizeRation: 初始内容 Size 的比例。也可以在 viewDidLoad 中使用 self.preferredContentSize 直接设置 Size。

使用说明:
远程和本地通知最终都可以使用此扩展自定义 UI,只需将通知的 categoryIdentifier(类型标示) 加入到 plist 中即可。

  • 本地推送时,确保设置的 content.categoryIdentifier(通知内容类型标示) 已加入 plist 中。
  • 远程推送,需要设置 category 字段,且确保值也已加入 plist 中。

4、UNNotificationServiceExtension (通知服务扩展)

UNNotificationServiceExtension 提供在远程推送将要被 push 出来前,处理推送显示内容的机会。此时可以对通知的 request.content 进行内容添加,如添加附件,userInfo 等。服务器推送实例:

{
  "aps" : {
    "alert" : {
      "title" : "title",
      "body" : "Your message Here"      
    },
     // 开启可变内容
    "mutable-content" : "1",   
    // 加入自定义数据,图片 url 路径
    "image":"http://....jpg"               
  }
}

示例代码:

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    NSDictionary *apsDic = [request.content.userInfo objectForKey:@"aps"];
    NSString *attachUrl = [apsDic objectForKey:@"image"];
    if(attachUrl){
        [self handlerImageWith:attachUrl];
    }
}

5、UNNotificationAction(通知响应事件)

代表一个响应通知的事件。可以为每个通知设置不同的交互事件。下拉推送通知或处在锁屏界面侧滑通知时,会出现交互按键。
交互事件主要分为以下两类:

  • UNNotificationAction:
    普通点击按键,可设置 identifier、 title 及 点击后的响应,例如:foreground 前台响应,destructive 点击后销毁通知,authenticationRequired 响应前是否需要解锁。甚至可以使用 UNNotificationAction + accessoryInputView 结合,达到加入自定义辅助输入控件的效果
  • UNTextInputNotificationAction:
    当然也可以直接使用系统类 UNTextInputNotificationAction 创建输入框,但是风格比较固定。

示例代码:

- (void)registerNotificationCategory{
    UNTextInputNotificationAction *inputAction = [UNTextInputNotificationAction actionWithIdentifier:@"action_reply" title:@"回复" options:UNNotificationActionOptionForeground];
    UNNotificationAction *cancelAction = [UNNotificationAction actionWithIdentifier:@"action_cancel" title:@"取消" options:UNNotificationActionOptionDestructive];
    
    UNNotificationCategory *saySomething = [UNNotificationCategory categoryWithIdentifier:saySomethingCategory actions:@[inputAction,cancelAction] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
    [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObject:saySomething]];
}

响应处理:

  • 若处于 UNNotificationContentExtension 通知扩展界面时,点击 【回复】按键会回调 UNNotificationContentExtension 扩展接口的方法:
// If implemented, the method will be called when the user taps on one
// of the notification actions. The completion handler can be called
// after handling the action to dismiss the notification and forward the
// action to the app if necessary.
- (void)didReceiveNotificationResponse:(UNNotificationResponse *)response completionHandler:(void (^)(UNNotificationContentExtensionResponseOption option))completion;{
    
}
  • 如果不支持 UNNotificationContentExtension则点击【回复】回调 UNUserNotificationCenterDelegate 中的方法:
// The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{

}

补充:iOS10中可以在前台中收到通知了,需要添加一下代码:

\\ notificationHandler实现UNUserNotificationCenterDelegate
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self.notificationHandler];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容