以下是一个使用本地通知与操作按钮的代码示例:
import UserNotifications
// 请求用户授权发送通知
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
if granted {
// 用户授权成功
print("用户授权成功")
} else {
// 用户授权失败
print("用户授权失败")
}
}
// 创建一个通知内容
let content = UNMutableNotificationContent()
content.title = "提醒"
content.body = "您有一条新消息"
content.sound = UNNotificationSound.default
// 创建一个操作按钮
let action = UNNotificationAction(identifier: "reply", title: "回复", options: [.foreground])
// 创建一个类别
let category = UNNotificationCategory(identifier: "message", actions: [action], intentIdentifiers: [], options: [])
// 将类别注册到通知中心
UNUserNotificationCenter.current().setNotificationCategories([category])
// 将操作按钮添加到通知内容中
content.categoryIdentifier = "message"
// 创建一个触发器,例如10秒后触发
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
// 创建一个通知请求
let request = UNNotificationRequest(identifier: "notification", content: content, trigger: trigger)
// 将通知请求添加到通知中心
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print("添加通知请求失败:\(error)")
} else {
print("添加通知请求成功")
}
}
这个示例代码使用UserNotifications框架创建本地通知,并添加了一个操作按钮。用户可以在通知显示时点击操作按钮执行相应的操作,例如回复消息。要使操作按钮生效,需要先注册一个包含操作按钮的类别,并将类别的标识符设置为通知内容的categoryIdentifier属性。在上述示例中,类别的标识符为"message",操作按钮的标识符为"reply",操作按钮的标题为"回复"。当用户点击操作按钮时,应用程序将进入前台并执行相应的操作。
上一篇:本地通知无效,如何修复?
下一篇:本地通知与倒计时