本文通过一个示例,演示 iOS 应用如何请求通知权限、添加交互式按钮以及处理通知响应。
一、核心功能概览
- 权限请求:用户授权通知弹窗、角标和声音。
- 通知发送:延迟或指定时间发送自定义内容通知。
- 交互处理:给通知添加自定义按钮并处理回调。
二、通知权限申请
在发送通知前,首先需要申请权限。
详细代码如下:
let center = UNUserNotificationCenter.current()
center = requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("获得授权")
} else {
print("未获得授权")
}
}
这里申请了三种权限:1. 弹窗(.alert)、2. 角标(.badge)、3. 声音(.sound)。
三、配置交互式通知
给指定的通知,添加自定义交互按钮。
let center = UNUserNotificationCenter.current()
// 需要当前类实现 UNUserNotificationCenterDelegate 协议,
// 用于处理通知上的按钮点击事件的回调
center.delegate = self
// 创建两个交互动作
let show = UNNotificationAction(
identifier: "show",
title: "显示更多",
// 点击启动应用
options: .foreground
)
let delete = UNNotificationAction(
identifier: "delete",
title: "删除",
// 标记为删除操作,点击后删除通知
options: .destructive
)
// 创建分类并注册
let category = UNNotificationCategory(
// 需要与 UNMutableNotificationContent 中的 content.categoryIdentifier 对应
identifier: "alarm",
actions: [show, delete],
intentIdentifiers: []
)
center.setNotificationCategories([category])
四、定时发送通知
定时通知可以设置为每日指定时间发送,或者设置为间隔多少时间后发送。
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "你好呀"
content.body = "这是一个通知消息"
// 关联交互分类,与上方的 UNNotificationCategory 中的 identifier 相同
content.categoryIdentifier = "alarm"
// 附加自定义数据
content.userInfo = ["customData": "helloworld"]
content.sound = .default
// 设置触发器:
// MARK: - 5 秒钟后触发
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
// MARK: - 每天早上 10 点 30 分重复触发
var dateComponents = DateComponents()
dateComponents.hour = 10
dateComponents.minute = 30
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
// 发送请求
let request = UNNotificationRequest(
identifier: UUID().uuidString,
content: content,
trigger: trigger
)
center.add(request)
五、通知响应处理
通过实现 UNUserNotificationCenterDelegate
协议的 userNotificationCenter
方法,即可实现对通知上的交互事件回调。
import UIKit
import UserNotifications
// 首先需要实现 UNUserNotificationCenterDelegate 协议
class ViewController: UIViewController, UNUserNotificationCenterDelegate {
// ...
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void
) {
let userInfo = response.notification.request.content.userInfo
if let customData = userInfo["customData"] as? String {
// 打印通知中附加的自定义信息
print("接收到自定义数据:\(customData)") // 接收到自定义数据:helloworld
// 根据动作标识(identifier)处理交互
switch response.actionIdentifier {
case UNNotificationDefaultActionIdentifier:
// 默认交互事件(即点击通知本身)
print("用户点击了通知")
case "show":
print("用户点击了 [显示更多]")
case "delete":
print("用户点击了 [删除]")
default:
break
}
}
// 处理完成后必须调用此回调
completionHandler()
}
}
六、设置图标角标
let center = UNUserNotificationCenter()
// 设置角标数字为 5
center.setBadgeCount(5)
// 清除角标
center.setBadgeCount(0)
七、完整代码
import UIKit
import UserNotifications
class ViewController: UIViewController, UNUserNotificationCenterDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Register", style: .plain, target: self, action: #selector(registerLocal))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Schedule", style: .plain, target: self, action: #selector(scheduleLocal))
}
@objc func registerLocal() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("获得授权")
} else {
print("未获得授权")
}
}
}
func registerCategories() {
let center = UNUserNotificationCenter.current()
center.delegate = self
let show = UNNotificationAction(identifier: "show", title: "显示更多", options: .foreground)
let delete = UNNotificationAction(identifier: "delete", title: "删除", options: .destructive)
let category = UNNotificationCategory(identifier: "alarm", actions: [show, delete], intentIdentifiers: [])
center.setNotificationCategories([category])
}
@objc func scheduleLocal() {
registerCategories()
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "你好呀"
content.body = "这是一个通知消息"
content.categoryIdentifier = "alarm"
content.userInfo = ["customData": "helloworld"]
content.sound = UNNotificationSound.default
// MARK: - 5 秒钟后触发
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
// MARK: - 每天早上 10 点 30 分重复触发
// var dateComponents = DateComponents()
// dateComponents.hour = 10
// dateComponents.minute = 30
// let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
}
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void
) {
let userInfo = response.notification.request.content.userInfo
if let customData = userInfo["customData"] as? String {
print("接收到自定义数据: \(customData)")
switch response.actionIdentifier {
case UNNotificationDefaultActionIdentifier:
print("用户点击了通知")
case "show":
print("用户点击了 [显示更多]")
case "delete":
print("用户点击了 [删除]")
default:
break
}
}
completionHandler()
}
}