iOS:推送通知,UIApplicationStateInactive和快速应用切换
根据苹果文件,为了找出一个用户是否敲你的推送通知,你应该检查applicationState
中的application:didReceiveRemoteNotification:
如果值是UIApplicationStateInactive,用户点击操作button; 如果值是UIApplicationStateActive,那么应用程序在收到通知时是最前面的。
我发现这并非总是如此。 例如:
双击主页button以显示系统托盘,并进入“快速应用程序切换模式”,您的应用程序向上滑动以显示其他正在运行的应用程序,并且您的应用程序处于非活动状态(即使它仍然可见)。 如果您在此模式下收到推送通知,则您的应用程序委托仍然会收到application:didReceiveRemoteNotification:
此时您的applicationState是UIApplicationStateActive
。 根据文档,你应该像对待用户一样对待它,但在这种情况下,他们没有。 不仅如此,用户甚至没有看到推送通知(可能是因为应用程序的顶部在此模式下被切断)。
有谁知道有一种方法来检测“快速应用程序切换模式”或正确处理通知?
我可以用一些漂亮的检查来修复它
从本质上来说,这件事的关键是
-(void)applicationDidEnterBackground:(UIApplication *)application;
当您进入快速应用程序切换(或控制中心)时不会调用此方法,因此您需要根据此设置进行检查。
@property BOOL isInBackground; @property (nonatomic, retain) NSMutableArray *queuedNotifications;
而当你收到通知…
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { UIApplicationState appState = application.applicationState; // Check if we're in this special state. If so, queue the message up if (appState == UIApplicationStateInactive && !self.isInBackground) { // This is a special case in which we're in fast app switching or control center if (!self.queuedNotifications) { self.queuedNotifications = [NSMutableArray array]; } // Queue this to show when we come back [self.queuedNotifications addObject:userInfo]; } }
然后当我们回来…
- (void)applicationDidBecomeActive:(UIApplication *)application { application.applicationIconBadgeNumber = 0; if (!self.isInBackground) { // Show your notifications here // Then make sure to reset your array of queued notifications self.queuedNotifications = [NSMutableArray array]; } }
还有一件事你可能想要做的是检查这个特殊的情况下,快速切换应用程序和用户去别的地方。 在设置isInBackground BOOL之前,我这样做。 我select将它们作为本地通知发送
-(void)applicationDidEnterBackground:(UIApplication *)application { for (NSDictionary *eachNotification in self.queuedNotifications) { UILocalNotification *notification = [self convertUserInfoToLocalNotification:eachNotification]; [[UIApplication sharedApplication] scheduleLocalNotification:notification]; } self.queuedNotifications = [NSMutableArray array]; self.isInBackground = YES; }