iOS10中PushNotification处理通知(持续更新)

之前已经说到了对通知的取消和更新,这篇文章咱们介绍通知的处理。

处理通知

应用内展示通知

现在系统可以在应用处于后台或者退出的时候向用户展示通知了。不过,当应用处于前台时,收到的通知是无法进行展示的。如果我们希望在应用内也能显示通知的话,需要额外的工作。
UNUserNotificationCenterDelegate 提供了两个方法,分别对应如何在应用内展示通知,和收到通知响应时要如何处理的工作。我们可以实现这个接口中的对应方法来在应用内展示通知:

class NotificationHandler: NSObject, UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, 
                       willPresent notification: UNNotification, 
                       withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) 
    {
        completionHandler([.alert, .sound])
        
        // 如果不想显示某个通知,可以直接用空 options 调用 completionHandler:
        // completionHandler([])
    }
}

实现后,将 NotificationHandler 的实例赋值给 UNUserNotificationCenterdelegate属性就可以了。没有特殊理由的话,AppDelegate 的 application(_:didFinishLaunchingWithOptions:)就是一个不错的选择:

class AppDelegate: UIResponder, UIApplicationDelegate {
    let notificationHandler = NotificationHandler()
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        UNUserNotificationCenter.current().delegate = notificationHandler
        return true
    }
}

对通知进行响应

UNUserNotificationCenterDelegate中还有一个方法,userNotificationCenter(_:didReceive:withCompletionHandler:)。这个代理方法会在用户与你推送的通知进行交互时被调用,包括用户通过通知打开了你的应用,或者点击或者触发了某个 action (我们之后会提到 actionable 的通知)。因为涉及到打开应用的行为,所以实现了这个方法的 delegate必须在 applicationDidFinishLaunching: 返回前就完成设置,这也是我们之前推荐将 NotificationHandler 尽早进行赋值的理由。

一个最简单的实现自然是什么也不错,直接告诉系统你已经完成了所有工作。

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    completionHandler()
}

想让这个方法变得有趣一点的话,在创建通知的内容时,我们可以在请求中附带一些信息:

let content = UNMutableNotificationContent()
content.title = "Time Interval Notification"
content.body = "My first notification"
content.userInfo = ["name": "onevcat"]

在该方法里,我们将获取到这个推送请求对应的 responseUNNotificationResponse是一个几乎包括了通知的所有信息的对象,从中我们可以再次获取到userInfo 中的信息:
更好的消息是,远程推送的 payload 内的内容也会出现在这个 userInfo 中,这样一来,不论是本地推送还是远程推送,处理的路径得到了统一。通过 userInfo 的内容来决定页面跳转或者是进行其他操作,都会有很大空间。

Actionable 通知发送和处理

注册 Category

iOS 8 和 9 中 Apple 引入了可以交互的通知,这是通过将一簇 action 放到一个 category 中,将这个 category 进行注册,最后在发送通知时将通知的 category 设置为要使用的 category 来实现的。
注册一个 category 非常容易:

private func registerNotificationCategory() {
    let saySomethingCategory: UNNotificationCategory = {
        // 1
        let inputAction = UNTextInputNotificationAction(
            identifier: "action.input",
            title: "Input",
            options: [.foreground],
            textInputButtonTitle: "Send",
            textInputPlaceholder: "What do you want to say...")
        
        // 2
        let goodbyeAction = UNNotificationAction(
            identifier: "action.goodbye",
            title: "Goodbye",
            options: [.foreground])
        
        let cancelAction = UNNotificationAction(
            identifier: "action.cancel",
            title: "Cancel",
            options: [.destructive])
        
        // 3
        return UNNotificationCategory(identifier:"saySomethingCategory", actions: [inputAction, goodbyeAction, cancelAction], intentIdentifiers: [], options: [.customDismissAction])
    }()
    UNUserNotificationCenter.current().setNotificationCategories([saySomethingCategory])
}
  1. UNTextInputNotificationAction 代表一个输入文本的 action,你可以自定义框的按钮 title 和 placeholder。你稍后会使用 identifier 来对 action 进行区分。
    2.普通的 UNNotificationAction 对应标准的按钮。
    3.为 category 指定一个 identifier,我们将在实际发送通知的时候用这个标识符进行设置,这样系统就知道这个通知对应哪个 category 了。

当然,不要忘了在程序启动时调用这个方法进行注册:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    registerNotificationCategory()
    UNUserNotificationCenter.current().delegate = notificationHandler
    return true
}

发送一个带有 action 的通知

在完成 category 注册后,发送一个 actionable 通知就非常简单了,只需要在创建 UNNotificationContent时把 categoryIdentifier设置为需要的 category id 即可:

content.categoryIdentifier = "saySomethingCategory"```
尝试展示这个通知,在下拉或者使用 3D touch 展开通知后,就可以看到对应的 action 了:
![](http://upload-images.jianshu.io/upload_images/3425795-083e2f1577a56a7b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
远程推送也可以使用 category,只需要在 payload 中添加 category 字段,并指定预先定义的 category id 就可以了:

{
"aps":{
"alert":"Please say something",
"category":"saySomething"
}
}

处理 actionable 通知

和普通的通知并无二致,actionable 通知也会走到 `didReceive` 的 delegate 方法,我们通过 request 中包含的` categoryIdentifier` 和 response 里的 `actionIdentifier` 就可以轻易判定是哪个通知的哪个操作被执行了。对于 `UNTextInputNotificationAction` 触发的 response,直接将它转换为一个 `UNTextInputNotificationResponse`,就可以拿到其中的用户输入了:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

if let category = UserNotificationCategoryType(rawValue: response.notification.request.content.categoryIdentifier) {
    switch category {
    case .saySomething:
        handleSaySomthing(response: response)
    }
}
completionHandler()

}

private func handleSaySomthing(response: UNNotificationResponse) {
let text: String

if let actionType = SaySomethingCategoryAction(rawValue: response.actionIdentifier) {
    switch actionType {
    case .input: text = (response as! UNTextInputNotificationResponse).userText
    case .goodbye: text = "Goodbye"
    case .none: text = ""
    }
} else {
    // Only tap or clear. (You will not receive this callback when user clear your notification unless you set .customDismissAction as the option of category)
    text = ""
}

if !text.isEmpty {
    UIAlertController.showConfirmAlertFromTopViewController(message: "You just said \(text)")
}

}

上面的代码先判断通知响应是否属于 “saySomething”,然后从用户输入或者是选择中提取字符串,并且弹出一个 alert 作为响应结果。当然,更多的情况下我们会发送一个网络请求,或者是根据用户操作更新一些 UI 等。
关于 Actionable 的通知,可以参考 Demo 中 [ActionableViewController](https://github.com/onevcat/UserNotificationDemo/blob/master/UserNotificationDemo/ActionableViewController.swift)
 的内容。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 点击查看原文 Web SDK 开发手册 SDK 概述 网易云信 SDK 为 Web 应用提供一个完善的 IM 系统...
    layjoy阅读 14,008评论 0 15
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,186评论 19 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,276评论 4 61
  • 真的他妈的很不爽 大冷天送餐慢 送到了图书馆不让进 请人开会都拒绝 真的好失败呵 妈了个逼
    4b058a89ab2c阅读 163评论 0 0
  • 图/文:茉莉 一、西湖十景之苏堤 徐风拂初荷,嫩柳蔽微波望苏堤漫漫,盼夫舟泊岸 (西湖景区以复古建筑的南山路为主干...
    茉莉的小茶馆阅读 326评论 3 6