1

我已经创建了一个预定的通知,并且我希望能够在它交付后做一些事情。不是在单击或选择它时,而是在它实际交付并显示在用户屏幕上时。

我用来生成通知的代码是:

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 中添加一些内容,以便在发送通知时做出响应,但我一直在寻找整个互联网并且找不到在交付时而不是在选择时执行此操作的方法.

4

1 回答 1

2

当通知到达时,系统调用userNotificationCenter(_:willPresent:withCompletionHandler:)UNUserNotificationCenter 对象的委托方法。

 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()
                }
        }
于 2018-05-07T18:53:11.203 回答