iOS10推送新框架UserNotifications

iOS10新增了UserNotifications和UserNotificationsUI两个新的推送框架,这是一个令人欣喜的改变,给了开发者更多的可操作空间。
这里没有推送服务器,先拿本地推送做例子吧,
首先设置推送触发时间,这里设置一秒之后触发

let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 1, repeats: false)

设置推送内容,iOS10中推送除了可以设置发送内容,还可以设置标题和副标题等

let content = UNMutableNotificationContent()
content.title = "Welcome"
content.body = "Welcome to my test"

如果是远程推送,则需要服务器返回如下格式的数据


{
  "aps" :
   {
   "alert" : {
   "title" : "Introduction to Notifications",
   "subtitle" : "Session 707",
   "body" : "Woah! These new notifications look amazing! Don’t you agree?"
  },
"badge" : 1},
}

下面创建发送通知请求

let request = UNNotificationRequest.init(identifier: "test", content: content, trigger: trigger)

最后把请求添加到通知中心

let center = UNUserNotificationCenter.current()
center.delegate = self
center.add(request, withCompletionHandler:nil)
center.requestAuthorization([.alert, .sound]){(granted, error) in}

收到通知后会调用UNUserNotificationCenterDelegate中的回调方法,在这里做APP内的处理

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound])
 }

UserNotifications框架里还添加了action的功能,可以在用户不打开APP的情况下处理消息,例如聊天应用收到朋友的消息,可以直接在APP外回复。
创建action

let action = UNNotificationAction(identifier: "reply", title: "Reply", options: [])

创建category绑定action

let category = UNNotificationCategory(identifier: "message", actions: [action], minimalActions: [action], intentIdentifiers: [], options: [])

设置content的categoryIdentifier属性,跟上面category的identifier一致

content.categoryIdentifier = "message"

最后将category设置到通知中心

center.setNotificationCategories([category])

收到通知后,点击上面设置的Reply按钮,也会调用UNUserNotificationCenterDelegate方法

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
        completionHandler(print("received"))
   }

以上介绍的都是新的推送框架的最基本用法,利用UserNotificationsUI框架,可以做更酷炫的操作,如UI定制,推送图片等,这些日后再写。

你可能感兴趣的:(iOS10推送新框架UserNotifications)