您需要设置一个委托PKPushRegistry
您创建的对象并将其指定为 VOIP 类型:
let voipRegistry = PKPushRegistry(queue: nil)
voipRegistry.delegate = myPushDelegate
voipRegistry.desiredPushTypes = [PKPushType.voIP]
您的代表必须遵守PKPushRegistryDelegate
协议。
然后,实施pushRegistry(_:didReceiveIncomingPushWith:for:completion:)
协议函数(参考 https://developer.apple.com/documentation/pushkit/pkpushregistrydelegate/2875784-pushregistry) - 该函数将在收到推送时被调用(即使应用程序已提前终止)。
功能说明:
通知委托人已收到远程推送。
指定的推送类型。一旦您完成,请立即调用完成处理程序
已完成有效负载的处理。当收到推送通知时调用此方法
请注意该函数:pushRegistry(_:didReceiveIncomingPushWith:for:)
已被弃用,所以不要与我上面提到的混淆。
有关的更多信息PKPushRegistryDelegate
协议:here https://developer.apple.com/documentation/pushkit/pkpushregistrydelegate
关于实际问题,有一个解决方法 - 这个想法是创建一个标志,当应用程序终止时该标志将被销毁,但一旦它醒来,它的状态就会改变 - 如果应用程序从后台唤醒标志状态将被保存,但如果应用程序在终止后唤醒,则标志将保持默认值。
在推送的委托类中:
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
}