要解决“本地通知没有被添加”的问题,可以按照以下步骤进行检查和修复:
import UserNotifications
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
if granted {
// 用户允许通知权限
} else {
// 用户拒绝通知权限
}
}
import UserNotifications
let content = UNMutableNotificationContent()
content.title = "提醒标题"
content.body = "提醒内容"
content.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "LocalNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print("添加本地通知失败:\(error.localizedDescription)")
} else {
print("本地通知已添加成功")
}
}
import UserNotifications
class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// 当应用程序在前台时,收到通知时的处理逻辑
// 可以选择是否显示通知的提示,例如:.alert, .sound, .badge
completionHandler([])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// 当用户点击通知时的处理逻辑
// 可以根据通知的标识符进行相应的操作
completionHandler()
}
}
// 设置通知中心的代理
let notificationDelegate = NotificationDelegate()
UNUserNotificationCenter.current().delegate = notificationDelegate
通过检查和修复以上代码,应该能够解决“本地通知没有被添加”的问题。