美文网首页iOS开发实用技巧
iOS10中PushNotification处理通知(持续更新)

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

作者: Arackboss | 来源:发表于2017-05-22 14:04 被阅读0次

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

处理通知

应用内展示通知

现在系统可以在应用处于后台或者退出的时候向用户展示通知了。不过,当应用处于前台时,收到的通知是无法进行展示的。如果我们希望在应用内也能显示通知的话,需要额外的工作。
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 了:
![](https://img.haomeiwen.com/i3425795/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)
 的内容。

相关文章

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

    之前已经说到了对通知的取消和更新,这篇文章咱们介绍通知的处理。 处理通知 应用内展示通知 现在系统可以在应用处于后...

  • iOS 推送回调方法整理

    不考虑iOS10以下。 APP在运行中收到通知的处理方法:执行UIApplicationDelegate代理方法 ...

  • iOS10调度组处理通知问题

    记近期处理iOS10的通知时遇到的一个坑: iOS10的取消未展示通知方法removePendingNotific...

  • iOS10中PushNotification大改革(未完待续..

    PushNotification发展历史 iOS 10 中,把以前杂乱的和通知相关的 API 都统一了,现在开发者...

  • ios 使用本地通知

    IOS10系统 app没有出现在系统设置-通知列表处理

  • iOS10的推送处理

    新版iOS10更新后, 通知的处理发生里很大变化, 本人也刚刚处理完成这一方面的问题, 写出来希望帮助更多的人, ...

  • iOS10关于通知的适配

    在更新了iOS10之后发现在通知部分出现了一些问题,原先的处理是:锁屏状态下接收到评论的推送通知之后滑动打开应用可...

  • 关于iOS通知那些事

    一、概述 通知分为本地通知和远程推送通知,iOS10中对于通知这一块改变较大,本文主要针对iOS10的通知,iOS...

  • ios10推送--从证书创建到消息处理

    ios10更新以来,推送改的还是很多的,让我们从头说来先说系统注册远程通知,ios10之后,注册方法变成了这样 注...

  • IOS的通知

    通知详解 简书-iOS10 推送通知 UserNotifications iOS10本地通知UserNotifi...

网友评论

    本文标题:iOS10中PushNotification处理通知(持续更新)

    本文链接:https://www.haomeiwen.com/subject/fvibxxtx.html