iOS推送通知和AppDelegate方法行为

uer*_*ceg 6 push-notification apple-push-notifications ios appdelegate

我对许多stackoverflow问题和网站进行了一些研究,试图弄清楚iOS推送通知如何影响AppDelegate生命周期方法以及何时触发哪种方法(而不是).该研究的主要焦点是"标准"iOS推送通知(带alert字段)和静默(通过content-available设置1)以及AppDelegate application:didReceiveRemoteNotificationapplication:didFinishLaunchingWithOptions方法.

我不想针对不同的场景问很多问题,而是试着写下我尝试过的不同测试用例的陈述,然后问你:

Is there any statement that is wrong and if yes, which one and why?


场景1:通过点击主页按钮使用应用程序并将其置于后台.

  1. 如果发送标准推送通知,则在推送通知到达时,没有任何方法被触发,应用程序在后台保持不活动状态.一旦点击推送通知并且应用程序因此而被打开,application:didReceiveRemoteNotification方法被调用并且application:didFinishLaunchingWithOptions不会被调用.我在将应用程序放到后台以及应用程序在后台运行超过一个小时之后立即测试了这种情况 - 相同的行为.我想如果由于某些原因iOS决定在后台杀死我的应用程序,这个测试用例就像场景2,从下面的声明1,对吧?

  2. 如果发送静默推送通知,则在推送通知到达的那一刻,application:didReceiveRemoteNotification方法被调用并且application:didFinishLaunchingWithOptions不被调用.


场景2:通过将其从正在运行的应用列表中滑出来使用和杀死应用.

  1. 如果发送标准推送通知,则在推送通知到达时,没有任何方法被触发,应用程序仍然被杀死.一旦点击推送通知并且应用程序因此而被打开,application:didReceiveRemoteNotification方法被调用并且application:didFinishLaunchingWithOptions不会被调用.

  2. 如果发送静默推送通知,则无法触发任何方法,因为无法将静默推送通知发送到被杀死的应用程序.在发送通知后打开应用程序后,application:didFinishLaunchingWithOptions作为正常流程的一部分进行调用,并且没有任何推送通知信息.application:didReceiveRemoteNotification没有被召唤.


如果您可以想到其他一些我可能忘记提及的现实生活场景,我会非常感激地了解它们以及在这些情况下会发生什么.

干杯


更新#1

感谢Sandeep Bhandari的更新和其他方案.我忘记在原来的问题中提到我正在探索应用程序到达目前not处于前台的应用程序的情况.

将Sandeep的场景添加到列表中:


场景3:正在使用应用程序并且推送通知到达.

  1. 如果发送标准推送通知,application:didReceiveRemoteNotification将调用方法.application:didFinishLaunchingWithOptions不会被打电话.

  2. 如果发送静默推送通知,application:didReceiveRemoteNotification则会调用方法.application:didFinishLaunchingWithOptions不会被打电话.


场景4:应用程序在后台运行.

  1. 如果发送标准推送通知,application:didReceiveRemoteNotification将调用方法.application:didFinishLaunchingWithOptions不会被打电话.

  2. 如果发送静默推送通知,application:didReceiveRemoteNotification则会调用方法.application:didFinishLaunchingWithOptions不会被打电话.


has*_*san 10

从经验和挖掘很多iOS推送通知.应用程序在前景或活着在背景中.两种情况都会触发相同的委托方法.只didReceiveRemoteNotification.

静默推送通知具有不同的处理程序:( content-available 1表示静默通知)

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    }
Run Code Online (Sandbox Code Playgroud)

当应用程序死了.didReceiveRemoteNotification从未要求定期推送通知.必须didFinishLaunchingWithOptions按以下方式处理:

// handle notification when app is closed.
let notification = launchOptions?[.remoteNotification]
if notification != nil {
    self.application(application, didReceiveRemoteNotification: notification as! [AnyHashable : Any])
}
Run Code Online (Sandbox Code Playgroud)

附加信息:

在app被杀时测试接收推送通知.从双击主页按钮时出现的列表中删除?

查看日志记录并进行调试的正确方法是编辑运行方案并选择Wait for executable to launch:

在此输入图像描述

从xcode运行应用程序.然后从服务器发送推送通知,然后点击通知中心的通知.