iOS10新增了UserNotifications和UserNotificationsUI兩個新的推送框架,這是一個令人欣喜的改變,給了開發(fā)者更多的可操作空間滨攻。
這里沒有推送服務器,先拿本地推送做例子吧,
首先設置推送觸發(fā)時間垦巴,這里設置一秒之后觸發(fā)
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 1, repeats: false)
設置推送內(nèi)容,iOS10中推送除了可以設置發(fā)送內(nèi)容铭段,還可以設置標題和副標題等
let content = UNMutableNotificationContent()
content.title = "Welcome"
content.body = "Welcome to my test"
如果是遠程推送骤宣,則需要服務器返回如下格式的數(shù)據(jù)
{
"aps" :
{
"alert" : {
"title" : "Introduction to Notifications",
"subtitle" : "Session 707",
"body" : "Woah! These new notifications look amazing! Don’t you agree?"
},
"badge" : 1},
}
下面創(chuàng)建發(fā)送通知請求
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}
收到通知后會調(diào)用UNUserNotificationCenterDelegate中的回調(diào)方法,在這里做APP內(nèi)的處理
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
UserNotifications框架里還添加了action的功能序愚,可以在用戶不打開APP的情況下處理消息憔披,例如聊天應用收到朋友的消息,可以直接在APP外回復爸吮。
創(chuàng)建action
let action = UNNotificationAction(identifier: "reply", title: "Reply", options: [])
創(chuàng)建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按鈕形娇,也會調(diào)用UNUserNotificationCenterDelegate方法
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
completionHandler(print("received"))
}
以上介紹的都是新的推送框架的最基本用法锰霜,利用UserNotificationsUI框架,可以做更酷炫的操作桐早,如UI定制癣缅,推送圖片等,這些日后再寫哄酝。