【问题标题】:Calling removeAllPendingNotificationRequests() in applicationWillTerminate not working on iPad在 applicationWillTerminate 中调用 removeAllPendingNotificationRequests() 在 iPad 上不起作用
【发布时间】:2020-04-25 23:23:20
【问题描述】:

我设置了一个虚拟项目来重现我看到的问题。在我的ContentView 中,我安排了一些重复通知。

struct ContentView: View {
    var body: some View {
        VStack {
            Button("Schedule notifications") {
                let content = UNMutableNotificationContent()
                content.title = "Title"
                content.body = "body"
                content.sound = UNNotificationSound.default
                let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
                let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
                UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
            }

            Button("Request Permission") {
                let current = UNUserNotificationCenter.current()
                current.requestAuthorization(
                    options: [.sound, .alert],
                      completionHandler: { completed, wrappedError in
                          guard let error = wrappedError else {
                              return
                          }
                  })
            }
        }

    }
}

然后在我的AppDelegate 中,我尝试在应用程序终止之前取消那些重复的通知。

   func applicationWillTerminate(_ application: UIApplication) {
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        print("============== removing all notifications")
    }

我发现我的预定通知仍然发送,即使我可以在 Xcode 控制台中看到我的打印语句。但是,如果我在 iPhone 上运行相同的测试,我的通知不会按预期传递。

是我做错了什么,还是这是一个错误?我在 iPad 上使用 13.4.1,在 iOS 上使用 13.3.1

【问题讨论】:

  • 只是为了缩小问题的来源。尝试从applicationWillTerminate 外部删除所有通知,看看它是否有效。如果还是不行,可以删除关于applicationWillTerminate的讨论...

标签: ios swift unusernotificationcenter unnotificationrequest unnotificationtrigger


【解决方案1】:

我也面临同样的问题。发现 applicationWillTerminate 方法有大约五秒钟的时间来执行任何任务并返回。并且 removeAllPendingNotificationRequests 立即返回,但在辅助线程中异步删除预定通知。

我认为清除通知所需的时间超过 5 秒。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-03
    • 2015-11-06
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多