ios - 应用程序如何确定它是否因 Voip 推送而从终止状态启动?

标签 ios

[注意:这个问题是关于 VoiP 推送的,而不是关于普通推送的] [注意 2:问题不在于如何设置应用程序以接收 Voip 推送,请正确阅读它实际询问的内容]。

如果应用程序终止并且 Voip 推送到达,则 didFinishLaunchingWithOptions 中的选项为零。 (例如,这可以与用户点击本地通知时启动应用程序形成对比)。

应用程序如何知道它是由于 VoIP 推送的到来而启动的,而不是应用程序已经在后台时推送到达?

最佳答案

您需要为您创建的 PKPushRegistry 对象设置一个委托(delegate),并将其指定为 VOIP 类型:

let voipRegistry = PKPushRegistry(queue: nil)
voipRegistry.delegate = myPushDelegate
voipRegistry.desiredPushTypes = [PKPushType.voIP]

您的委托(delegate)必须遵守 PKPushRegistryDelegate 协议(protocol)。

然后,实现 pushRegistry(_:didReceiveIncomingPushWith:for:completion:) 协议(protocol)函数 ( reference ) - 这个函数将在收到推送时被调用(即使在应用程序被终止时早先)。

功能说明:

Notifies the delegate that a remote push has been received.

the specified push type. Call the completion handler as soon as you have finished processing the payload.This method is invoked when a push notification has been received for

请注意函数:pushRegistry(_:didReceiveIncomingPushWith:for:) 已被弃用,所以不要与我上面提到的函数混淆。

关于 PKPushRegistryDelegate 协议(protocol)的更多信息:here

关于实际问题,有一个解决方法 - 这个想法是创建一个标志,当应用程序终止时将被销毁,但一旦它醒来,它的状态就会改变 - 如果应用程序从背景标志状态将被保存,但如果应用程序在终止后唤醒,标志将保持默认值。

在推送的委托(delegate)类中:

import PushKit
class PushDelegate: PKPushRegistryDelegate  {

    var flag = false

      func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, forType type: PKPushType) {
            if flag {
                print("the app woke up from background")
            } else {
                print("the app was terminated")
                flag = true
            }
        }
}

此外,为了检测用户是否启动了应用(这是应用处于事件状态的唯一情况),请使用以下代码:

let state = UIApplication.shared.applicationState

    if state == .background {

        // background
    }
    else if state == .active {

        // foreground
    }

关于ios - 应用程序如何确定它是否因 Voip 推送而从终止状态启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46981293/

相关文章:

ios - 使用 iOS SDK 通过 Amazon S3 存储和检索文件

ios - 在不使用 ios 通知的情况下唤醒 ios 应用程序

ios - 如何对字符串的日期进行排序?

javascript - 如果在 ajax 成功函数上调用,声音将不会播放

ios - 为什么 __weak 变量没有在自动释放池中注册?

ios - 使用缓存中的图像创建图像数组 (Swift)

ios - 在构建服务器上构建 iPhone 应用程序

ios applicationwillenterbackground 未被调用

html - 查找表中几行的 XPath?

使用多个 UIGestureRecognizers 关闭 iOS 键盘