gpt4 book ai didi

ios - 当应用程序处于后台时替代 UserNotificationCenter Delegate 的 willPresent

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:23:44 27 4
gpt4 key购买 nike

我想弄清楚我是否可以通过本地通知来实现我的目标,或者我是否需要切换到远程通知。

我正在通过构建一个闹钟程序来练习 iOS 10/Swift 3,该程序会在一天中的固定时间播放 RSS 更新的广播节目的最新一集。当应用程序在前台时,这很容易通过 UNUserNotificationCenterDelegate 的 willPresent 函数执行。我只是使用 willPresent 获取最新一集,并通过 AVAudio Player 播放。

当然,如果应用只在前台工作,这个功能就非常有限。我希望该应用程序在后台或关闭时以相同的方式工作。

我可以从文档中看到,当应用程序不在前台时,willPresent 不会运行。当应用程序在后台时,是否有另一种方法让本地通知在推送通知之前执行代码?或者我必须切换到远程通知吗?我看到 this answer to a related question但我想知道是否有更优雅的方法。

最佳答案

对于 iOS 10 本地通知 你真倒霉。

对于 iOS 10 远程通知无论用户交互如何 您都可以使用 application(_:didReceiveRemoteNotification:fetchCompletionHandler:) 接收回调. (令人困惑的是,他们弃用了大多数与通知相关的方法,但不是这个)


当应用程序处于前台并且您将要显示通知时的回调:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let content = notification.request.content
// Process notification content

completionHandler([.alert, .sound]) // Display notification as regular alert and play sound
}

当应用处于后台或前台并且用户点击操作时的回调:

enter image description here

例如为您提供用户点击保存 的回调。

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let actionIdentifier = response.actionIdentifier

switch actionIdentifier {
case UNNotificationDismissActionIdentifier: // Notification was dismissed by user
// Do something
completionHandler()
case UNNotificationDefaultActionIdentifier: // App was opened from notification
// Do something
completionHandler()
default:
completionHandler()
}
}

当应用程序处于后台、前台或(可能)暂停状态并且推送通知(远程或静默通知)到达时的回调:

在 iOS10 之前,当您点击通知时,application(_:didReceiveRemoteNotification:fetchCompletionHandler:) 会被调用。

但由于 iOS 10 application(_:didReceiveRemoteNotification:fetchCompletionHandler:) 不会在点击 时调用。它仅在远程通知到达 时调用。 (它在前台和后台都被调用)


对于 iOS 10 之前的版本,您可以只使用旧的 didReceiveLocalNotification 函数并捕获任何通知的到来。

关于ios - 当应用程序处于后台时替代 UserNotificationCenter Delegate 的 willPresent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44425744/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com