WWDC2018-如何自定义分组通知

1,374 阅读2分钟

最后更新: 2018-6-11 修正错别字

祝愿今年的高考考生超长发挥。

WWDC2016年的时候, 苹果发布了 UNNotification.framework, 让用户体验到了全新的通知查看功能。 在今年WWDC的时候, Apple 对此功能进行了提升, 增加了通知消息 Grouped 的功能。

试想, 如果你每天微信很繁忙, 有各种群组, 有好友等的, 每天通知一堆堆, 如果能将其进行分组显示, 想想都很棒。 废话不多说, 先附上今年的WWDC地址

这个视频主要介绍了四个方面的内容:(翻译不好, 就直接上原话了)

  • Notification groups
  • App grouping
  • Custom grouping
  • Group summaries

在我边观看边看api的过程中, 实际上也就是 Custom groupingGroup summaries 需要开发者注意点, 实际用起来真的非常的简单。

1. Notification groups

Notification groups 实际上说明, 每个应用的通知是可以按照组来区分的, 而且可以统一的管理(Manager、View、Clear All).

每个应用都可以 Grouped 起来, 当 View 某个 Grouped 的时候, 就可以展开查看单个 Grouped 的详细了。

2. App grouping

放两张图给你们看 你们就明白了。

3. Custom grouping

并不是所有的 App 只能定义在一个 Group 里面, 开发者可以根据具体的需求来进行定制。 当然用的是 iOS10 之后推出的 UNNotification.framework 框架。 不熟悉这个框架的童鞋可前往这里查看。

通过设置 threadIdentifier 可以将通知进行分组, 当你对通知设置了同一个的 threadIdentifier 之后, 这一类的通知在一定数量后会自动的进行分组。默认为 nil。 如果你对不同的通知设置不同的 threadIdentifier 的话, 那么这些不同的是不会被 Grouped 到一起的。。

// 简单的循环添加通知分组, 测试使用
func localNotification() {
        
        for i in 0..<10 {
            let notificationContent = UNMutableNotificationContent()
            notificationContent.title = "标题 \(i)"
            notificationContent.subtitle = "副标题\(i)"
            notificationContent.body = "内容\(i)"
            notificationContent.threadIdentifier = "LocalNotification"
            notificationContent.launchImageName = ""
            notificationContent.sound = UNNotificationSound.default
            let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
            let request = UNNotificationRequest(identifier: "localNotication\(i)", content: notificationContent, trigger: trigger)
            Thread.sleep(forTimeInterval: 0.5)
            UNUserNotificationCenter.current().add(request) { (error) in
            }
        }
        
        Thread.sleep(forTimeInterval: 300)        
        UNUserNotificationCenter.current().removeAllDeliveredNotifications()
    }

当然, 你可以可以通过配置文件来设置:

{
	"aps": {
		"alert": {
			"title": "标题",
			"body": "内容",
		}
		"thread-id": "notification-threadIdentifier"  // 配置这行
	}
}

下午用模拟器跑,运行出错,后面用真机跑, 发现了有bug: 我第二次删除app 测试, 然后就通知就显示不出来了, 在系统设置里面也看不到我的App。 图 后面补上。

4. Group summaries

开发者可以通过如下方式配置:

let summaryFormat = "%u more messages"
        
UNNotificationCategory(identifier: "category-identifier",
                       actions: [],
                       intentIdentifiers: [],
                       hiddenPreviewsBodyPlaceholder: nil,
                       categorySummaryFormat: summaryFormat,
                       options: [])

如果是 Grouped 的通知, 可以利用属性 summaryArgument 来配置。

同样, 你可以通过配置文件来设置

{
	"aps": {
		"alert": {
			"title": "标题",
			"body": "内容",
			"summary-arg": "notification-summaryArgument" // 配置这行
			"summary-arg-count": 3 
		}
		...
	}
}

最后提一个summaryArgumentCount。 这个也很有意思, 就等待你们自己去开发了。。。。。