iOS推送的众多坑

时间:2022-08-09 11:54:37

新来的一家公司,昨天和同事解决推送问题(工程里有集成百度推送和环信即时通讯),信誓旦旦的声称:" app在前台和后台运行时,推送触发的是didReceiveRemoteNotification事件, app在杀死状态时,推送触发的是didFinishLaunchingWithOptions事件"结果通过一阵试验之后,啪啪打脸了.居然都走了:"

application:(UIApplication )application didReceiveRemoteNotification:(NSDictionary )userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

"这个代理方法
因为众多项目中都是以这个为认知来做的,并且没有发生过任何问题,我表示不服了.在通过一系列的排查之后.冷静的去看了"

application:(UIApplication )application didReceiveRemoteNotification:(NSDictionary )userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

"的苹果相关注释.
注释是这样的:This delegate method offers an opportunity for applications with the "remote-notification" background mode to fetch appropriate new data in response to an incoming remote notification. You should call the fetchCompletionHandler as soon as you're finished performing that operation, so the system can accurately estimate its power and data cost.

This method will be invoked even if the application was launched or resumed because of the remote notification. The respective delegate methods will be invoked first. Note that this behavior is in contrast to application:didReceiveRemoteNotification:, which is not called in those cases, and which will not be invoked if this method is implemented.

话说这个方法其实7.0之后就已经有了,算是人性化的一个更新吧,然而萌萌的我并不知道.一直在分别实现didReceiveRemoteNotification和didFinishLaunchingWithOptions;

顺便提醒大家一句,现在市面上的博客里面大部分还是和我一样的认知状态,互相转载也好,没有踩到也罢.反正我这次是栽了,一顿饭出去了并且深深地毁我三观啊.

本人之前做的项目一直都是使用信鸽推送,并贴出信鸽文档如下:

iOS推送结果

  1. app在前台运行时,不弹出推送框,但是app通过代码可以获取到推送的消息。

  2. app在后台运行或者杀死状态时,会弹出推送框并且可以通过代码获取到推送的消息。

  3. app在前台和后台运行时,推送上报触发的是didReceiveRemoteNotification事件。

  4. app在杀死状态时,推送上报触发的是didFinishLaunchingWithOptions事件。

用户能接收到的如下:

  1. 用户进入App,按home键,发送信鸽消息,可以接收到弹窗和通知中心的通知;

  2. 用户进入App,按home键,进程杀掉,可以接收到弹窗和通知中心的通知;

  3. 用户进入App,保持在App中,后台可以接收到信鸽消息,但是前台没有弹窗和通知中心通知。

声明一下,这个说法确实是有问题的.虽然杀死状态下,点击推送条启动应用时didFinishLaunchingWithOptions的

launchOptions参数里确实包含推送信息.但是现在的系统原生方法并非只走didFinishLaunchingWithOptions了.切莫在didFinishLaunchingWithOptions和didReceiveRemoteNotification:fetchCompletionHandler方法中同时实现

实现方式:didReceiveRemoteNotification与didFinishLaunchingWithOptions分别实现远程推送处理或者直接didReceiveRemoteNotification:fetchCompletionHandler方法处理

顺便提醒一下萌新,即时通讯时候聊天消息注意区分远程推送和本地推送,响应代理方法不同,在此不多说了,主要记录一下今天这个坑.