本地推送通知UserNotifications在Swift中的实现方式

这篇文章主要介绍了本地推送通知UserNotifications在Swift中的实现方式,想了解消息推送的同学,一定要看一下

消息推送回调代理

接收用户对消息推送的反馈事件,比如说应用在后台收到了通知,用户点击了这条通知进入到了APP里面,我们需要获取这个事件去做一些处理,比如跳去某个界面,这里例子不讲这么复杂,只通过简单地判断用户是通过哪个通知进来的。

接收回调代理事件前,需要遵循UNUserNotificationCenterDelegate协议,并设置delegate接收的对象。


xtension AppDelegate: UNUserNotificationCenterDelegate {}

UNUserNotificationCenter.current().delegate = self

在Swift语言中,可以通过extension扩展类遵循的协议,并在extension。

当应用在前台运行时,收到的是这个-userNotificationCenter:willPresentNotification:withCompletionHandler:代理方法。UNNotification对象存储了传递到应用的一些数据,通过此对象可以拿到此条通知关联的触发器notification.request.trigger,从而判断其类型。


func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    guard let trigger = notification.request.trigger else { return; }
    if trigger.isKind(of: UNTimeIntervalNotificationTrigger.classForCoder()) {
        print("Notification did receive, Is class UNTimeIntervalNotificationTrigger")
    } else if trigger.isKind(of: UNCalendarNotificationTrigger.classForCoder()) {
        print("Notification did receive, Is class UNCalendarNotificationTrigger")
    }
}

当应用在后台,或者被杀死的状态下,收到的是这个-userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:代理方法。此方法接收UNNotificationResponse类型的参数,它里面包含notification属性,因此可以参考上面的代码进行触发器的判断。


func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    guard let trigger = response.notification.request.trigger else { return; }
    if trigger.isKind(of: UNTimeIntervalNotificationTrigger.classForCoder()) {
        print("Notification did receive, Is class UNTimeIntervalNotificationTrigger")
    } else if trigger.isKind(of: UNCalendarNotificationTrigger.classForCoder()) {
        print("Notification did receive, Is class UNCalendarNotificationTrigger")
    }
}

总结

本地通知有三种类型的触发器,分别是UNTimeIntervalNotificationTrigger、UNCalendarNotificationTrigger和UNLocationNotificationTrigger。

UNTimeIntervalNotificationTrigger在设置循环通知时,所设定的时间隔不能低于60秒,否则会报运行时错误。

Demo 源码下载

我已经把 Demo 上传至 GitHub 上面,项目名字是 SwiftUI-Tutorials,https://github.com/GarveyCalvin/SwiftUI-Tutorials,目录名为GCLocalUserNotification,有需要的朋友可以去下载运行一下,当然你也可以跟着文章去做一遍,这样更有利于你掌握此方面的知识。

以上就是本地推送通知UserNotifications在Swift中的实现方式的详细内容,更多关于Swift推送的资料请关注编程学习网其它相关文章!

本文标题为:本地推送通知UserNotifications在Swift中的实现方式