首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何识别UNUserNotificationCenter是随之而来的(:is )

如何识别UNUserNotificationCenter是随之而来的(:is )
EN

Stack Overflow用户
提问于 2022-11-30 06:08:56
回答 1查看 49关注 0票数 0

在这里,我使用UNUserNotificationCenter反复触发通知。当通知被触发时,我遇到了问题,我想在不采取任何行动的情况下调用函数。有人能告诉我怎么做吗?

代码语言:javascript
复制
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print(" Foreground Notification IS CALLED ")
        completionHandler([.badge, .banner, .sound])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print(" Nikan Did recieve calling ")

        if response.actionIdentifier == "Okay" {
            print(" Notification Clickced ")
        }
        completionHandler()
    }

    func createNotification() {
        let content = UNMutableNotificationContent()
        content.title = "Notification"
        content.subtitle = "Wow, Notification"
        content.categoryIdentifier = "Actions"
        content.sound = UNNotificationSound.defaultRingtone

        // show this notification five seconds from now
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
        // choose a random identifier
        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

        // notification actions
        let okay = UNNotificationAction(identifier: "Okay", title: "Okay", options: .destructive)
        let category = UNNotificationCategory(identifier: "Actions", actions: [okay], intentIdentifiers: [], options: [])

        UNUserNotificationCenter.current().setNotificationCategories([category])

        //    UNUserNotificationCenter.current().add(request)
        UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
            if let error = error {
                // Something went wrong
                print(error)
            }
        })
    }

当触发UNUserNotificationCenter的通知时,我需要一个响应来调用一个函数。

EN

回答 1

Stack Overflow用户

发布于 2022-12-01 05:27:44

问:当收到通知时,如何调用函数?

答:当你收到通知时(:in ),发布NSNotification并在你的UIViewController中观察它。在观察者的#selecteor方法中调用函数。

当点击推送通知时,DidReceive会触发,在您的情况下,应用程序处于后台,如果应用程序是通过单击push通知打开的,那么DidReveive将被触发。

代码语言:javascript
复制
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let pushInfo = response.notification.request.content.userInfo
// post NSNotification here
// You also have data fetched from push notification (if any) in pushInfo variable
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74623515

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档