UserNotifications

2020-11-27  本文已影响0人  lcc小莫

iOS10新增加了一个UserNotificationKit(用户通知框架)来整合通知相关的API,下面简单介绍一下新特性。
1.丰富了推送内容:现在可以设置推送的title、subtitle、body 以及符合大小的图片、音频、视频等附件内容。
2.可以操作管理通知:可以对通知进行查看、更新、删除。
3.优雅的展示方式:可以设置应用在前台展示通知。
对iOS10而言,UserNotificationKit(用户通知框架)是一种系统层面的UI展示,远程通知APNS只是通知的一种触发方式,UserNotificationKit的重要意义在于统一了Remote(远程通知)和Local(本地通知)。

本地通知

UserNotificationKit的基本使用流程
1.注册通知: 获取相关权限,注册APNS
2.发送通知: 创建通知并发起通知请求
3.处理通知: 处理通知回调,查找,移除,更新等


category.jpeg
1. 注册通知

UNUserNotificationCenter 用以管理与通知相关的行为。如果想要使用通知的话,必须先获取用户的授权,才可使用 requestAuthorization 方法。

// 请求通知权限
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) {
    (accepted, error) in
    if !accepted {
        print("用户不允许消息通知")
    }else {
        print("用户允许消息通知");
    }
}
2.发送通知

发送通知主要包括通知的内容:
1.设置推送内容

// 设置推送内容
let content = UNMutableNotificationContent()
content.title = "测试标题"
content.subtitle = "测试副标题"
content.body = "测试内容"
content.badge = 2
content.categoryIdentifier = "categoryIdentifier" //category标识,操作策略
content.sound = UNNotificationSound.default

// Media Attachments 发送附件:图片,音频,视频
通过本地磁盘上的文件 URL 创建一个 UNNotificationAttachment 对象,然后将这个对象放到数组中赋值给 content 的 attachments 属性:
let imageName = "icon_goods"
guard let imageURL = Bundle.main.url(forResource: imageName, withExtension: "png") else { return }
let attachment = try! UNNotificationAttachment(identifier: imageName, url: imageURL, options: .none)
content.attachments = [attachment]

2.设置通知触发器(4种触发器)
UNPushNotificationTrigger 触发APNS服务,系统自动设置(这是区分本地通知和远程通知的标识)
UNTimeIntervalNotificationTrigger 一段时间后触发
UNCalendarNotificationTrigger 指定日期触发
UNLocationNotificationTrigger 根据位置触发,支持进入某地或者离开某地或者都有。

// UNTimeIntervalNotificationTrigger 延时触发
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)

// UNCalendarNotificationTrigger  定时执行
let dateComponents = NSDateComponents()
let hour = "21"
let minute = "23"
dateComponents.hour = Int(hour)!
dateComponents.minute = Int(minute)!
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents as DateComponents, repeats: false)

3.添加通知

//设置请求标识符
let requestIdentifier = "categoryIdentifier"
//设置一个通知请求
let request = UNNotificationRequest(identifier: requestIdentifier,
                                content: content, trigger: trigger)
//将请求添加到发送中心
UNUserNotificationCenter.current().add(request) { error in
    if error == nil {
        print("添加推送成功!")
    }
}

4.通知策略(category+action)
action:设置标识(identifier)、按钮标题(title)、按钮选项(options)
options:
UNNotificationActionOptionAuthenticationRequired  执行前需要解锁确认
UNNotificationActionOptionDestructive  显示高亮(红色)
UNNotificationActionOptionForeground  将会引起程序启动到前台
action 有2种类型:
UNNotificationAction 普通按钮样式
UNTextInputNotificationAction 输入框样式

//把category添加到通知中心
center.setNotificationCategories([newsCategory])
//创建category
let newsCategory: UNNotificationCategory = {
    let intoAppAction = UNNotificationAction(
        identifier:  "id",
        title: "进入应用",
        options: [.foreground])
    
    let ignoreAction = UNNotificationAction(
        identifier:  "destructive",
        title: "忽略",
        options: [.destructive])
    
    return UNNotificationCategory(identifier:"categoryIdentifier",
                                  actions: [intoAppAction,ignoreAction],
                                  intentIdentifiers: [], options: [.customDismissAction])
}()

3.处理通知

常规处理
在创建通知请求时,我们已经指定了标识符。iOS10中我们可以通过标识符来管理处理通知。UserNotificationKIt提供了一系列API ,通过request的identifier,进行通知的查找、更新、删除。这个标识是用来区分这个通知和其他通知的。

1.查找通知
// 获取所有等待递送的通知
UNUserNotificationCenter.current().getPendingNotificationRequests { (request) in
 }
// 获取所有已经递送的通知
UNUserNotificationCenter.current().getDeliveredNotifications { (noti) in
}
2.更新通知
远程推送可以进行通知的更新
更新:center 的 addNotificationRequest:withCompletionHandler: 方法在 id 不变的情况下重新添加,就可以刷新原有的推送。
3.删除通知/取消通知
//删除已经递送的通知
 UNUserNotificationCenter.current().removeAllDeliveredNotifications() 
//删除所有等待递送的通知
 UNUserNotificationCenter.current().removeAllPendingNotificationRequests() 
//删除特定已经递送的通知(identifier)
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ['Identifier'])
//删除特定等待递送的通知(identifier)
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["Identifier"])
通知的回调处理UNUserNotificationCenterDelegate
UNUserNotificationCenter遵循UNUserNotificationCenterDelegate代理
//在应用内展示通知
func userNotificationCenter(_ center: UNUserNotificationCenter,
                       willPresent notification: UNNotification,
                       withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
    completionHandler([.alert, .sound,.badge])

    // 如果不想显示某个通知,可以直接用空 options 调用 completionHandler:
    // completionHandler([])
}
//对通知进行响应,收到通知响应时的处理工作,用户与你推送的通知进行交互时被调用;
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    completionHandler()
}

当打开应用时移除小红点
func applicationWillEnterForeground(_ application: UIApplication) {
    // 可以在此处移除通知
    NoticeManeger().removeNotice()
    application.applicationIconBadgeNumber = 0
}
Notification Extension

iOS 10 中添加了很多 extension,作为应用与系统整合的入口。与通知相关的 extension 有两个:Service Extension 和 Content Extension。前者可以让我们有机会在「接收到推送之后、展示推送之前」对通知内容进行修改;后者可以用来自定义通知视图的样式。

Service Extension(只对远程推送APNS的通知起效, 这里不做详细介绍)
Service Extension:可以对推送进行处理,更改、替换原有的内容。他可以对通知内容进行加密,也可以给推送展示内容添加附件(比如照片、背景音乐),使得内容更加丰富。
Content Extension:可以用来自定义通知的详细页面视图
1.创建NotificationContent,会生成NotificationViewController类,storyboard和info.plist
2.必须实现didReceive方法,
3.MainInterface.storyboard可以对UI进行修改,
4.Info.plist。可以通过 Info.plist 控制通知详细视图的尺寸,以及是否显示原始的通知;UNNotificationExtensionCategory要对应center注册时的Identifier;


ContentExtension.jpeg

iOS12新特性

Grouped notifications 推送分组
Notification content extensions 推送内容扩展中的可交互和动态更改Action
Notification management 推送消息的管理
Provisional authorization 临时授权
Critical alerts 警告性质的推送
########1.推送分组
自动:苹果会优先根据threadIdentifier进行分组,否则则会根据应用分组;
按App:设置按App,则自定义会失效,会根据应用分组;
关闭:使用无分组样式;

content.threadIdentifier = UUID().uuidString
2. 摘要Summary

当苹果把消息归拢到一起时,比如会显示:有xxx条消息来自xxx。具体文案根据自己设置。
也可以通过 let summaryFormat = NSString.localizedUserNotificationString(forKey: "NOTIFICATION_SUMMARY", arguments: nil) 来进行本地化服务

let likeAction = UNNotificationAction(
    identifier: "likeAction",
    title: "Like",
    options: [.authenticationRequired])
let reactAction = UNNotificationAction(
    identifier: "reactAction",
    title: "React",
    options: [.authenticationRequired])
if #available(iOS 12.0, *) {
    return UNNotificationCategory(identifier:"categoryIdentifier",
                                  actions: [likeAction,reactAction],
                                  intentIdentifiers: [],
                                  hiddenPreviewsBodyPlaceholder:"新的消息",
                                  categorySummaryFormat:"还有%u条来自%@的消息",
                                  options: [.customDismissAction])
}
IMG_F8992CDF880D-1.jpeg
3.推送内容扩展中的可交互和动态更改Action

比如设置喜欢action,点赞action,用户点击action时,可以在UI进行变化;

在Content Extension类中实现下面的方法
func didReceive(_ notification: UNNotification) {
}
func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) {
}
具体功能实现根据功能需求。
IMG_9928.PNG
IMG_9929.PNG
4.隐式推送

隐式推送目的是为了保护用户隐私。当用户设置了隐式推送,只能在通知中心中查看消息,锁定屏幕时,没有横屏展示,也没有标记和声音。
具体设置:1.可以在设置-通知,只打开消息中心;
2.可以在有消息推送过来时,左滑有个管理按钮,设置隐式推送或者显式推送;
值得注意的是,当我们请求通知权限时,有个provisional属性,如果设置了该属性,则用户在通知中心中会收到消息,但是会有一个用户选择的权限,用户可以选择继续接收,或者关闭。点击继续接收时,也可以设置隐式推送,或者显式推送。

//请求通知权限
center.requestAuthorization(options: [.alert, .sound, .badge,.provisional]) {
    (accepted, error) in
    if !accepted {
        print("用户不允许消息通知")
    }
}

IMG_9925.PNG
上一篇下一篇

猜你喜欢

热点阅读