【发布时间】:2022-08-19 01:20:56
【问题描述】:
我使用这些两个类来管理应用程序中的本地通知,问题是当我点击通知操作按钮“标记为已完成”时,它并没有使操作只是将我带到应用程序,所以我如何可以让通知动作按钮响应动作吗?
通知管理器类
internal final class LocalNotificationManager {
private static let center = UNUserNotificationCenter.current()
// MARK: Ask for permission
static func askUserPermissionToSendNotifications() {
self.center.requestAuthorization(options: [.alert, .badge, .sound]) { (success, error) in
if success {
// Do something if user allowing notifications
} else if !success {
// Do something if user do not allow the notifications
} else if let error = error {
// Show some message
print(error.localizedDescription)
}
}
}
// MARK: Schedul Notification
static func schedulNotification(for taskModel: TaskModel) {
let content = UNMutableNotificationContent()
content.interruptionLevel = .timeSensitive
content.body = taskModel.text
content.subtitle = \"\\(taskModel.priority != .none ? \"\\(taskModel.priority.rawValue) Priority\" : \"\")\"
content.categoryIdentifier = \"Task Actions\" // Same Identifier in registerCategories()
content.sound = UNNotificationSound.default
let taskIdentifier = taskModel.id.uuidString
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: taskIdentifier, content: content, trigger: trigger)
let localNotificationDelegate = LocalNotificationDelegate()
self.center.delegate = localNotificationDelegate
let markAsCompleted = UNNotificationAction(identifier: \"MARK_AS_COMPLETED\", title: \"Mark as Completed\", options: .foreground)
let placeholder = \"Task\"
let category = UNNotificationCategory(identifier: \"Task Actions\", actions: [markAsCompleted], intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: placeholder) // // Same Identifier in schedulNotification()
self.center.setNotificationCategories([category])
self.center.add(request)
}
}
通知代表
internal final class LocalNotificationDelegate: NSObject, ObservableObject, UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if response.actionIdentifier == \"MARK_AS_COMPLETED\" {
// its didn\'t print the message when I tap the action button
print(\"MARK_AS_COMPLETED Tapped\")
}
completionHandler()
}
}
-
将
localNotificationDelegate存储在属性中,因为一旦函数返回并在UNUserNotificationCenter中清除它就会被删除,因为它在那里很弱。 -
感谢“Asperi”它的工作知道,但是当我点击该动作时,它应该做出动作并关闭通知,但知道它会做出动作并打开应用程序。
-
我喜欢如何在不打开应用程序的情况下对通知操作按钮进行操作,在堆栈溢出问题中的“在 iOS 中单击本地通知时不要打开应用程序”,您只需要删除“选项” \" 在创建操作按钮时的 \"UNNotificationAction\" 中。
标签: swift swiftui localnotification