我已经创建了一个预定的通知,我希望能够在交付后做一些事情。不是一次点击或选择,而是当它实际发送并显示在用户的屏幕上时。
我用来生成通知的代码是:
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "foo", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "bar", arguments: nil)
var dateInfo = DateComponents()
dateInfo.hour = 7
dateInfo.minute = 0
print(dateInfo.hour!)
print(dateInfo.minute!)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: false)
// Create the request object.
let notificationRequest = UNNotificationRequest(identifier: "MorningAlarm", content: content, trigger: trigger)
center.add(notificationRequest)
我确信我必须在我的AppDelegate上添加一些内容,这些内容会在通知发送时做出响应,但我一直在寻找互联网,而无法在交付时找到方法而不是选择。
答案 0 :(得分:1)
当通知到达时,系统会调用UNUserNotificationCenter对象的委托的userNotificationCenter(_:willPresent:withCompletionHandler:)
方法。
let center = UNUserNotificationCenter.current()
center.delegate = self // What delegation target Here is my AppDelegate
extension AppDelegate : UNUserNotificationCenterDelegate {
// while your app is active in forground
// Handle Notifications While Your App Runs in the Foreground
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// Change this to your preferred presentation option
// Play a sound.
// completionHandler(UNNotificationPresentationOptions.sound)
}
// While App is inactive in background
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// While App is inactive in background
print(userInfo)
completionHandler()
}
}