iOS:推送通知、UIApplicationStateInactive 和快速应用切换

标签 ios push-notification uiapplicationdelegate

根据 Apple 文档,为了查明用户是否点击了您的推送通知,您应该检查 application:didReceiveRemoteNotification 中的 applicationState :

If the value is UIApplicationStateInactive, the user tapped the action button; if the value is UIApplicationStateActive, the application was frontmost when it received the notification.

我发现这并不总是正确的。例如:

双击主页按钮以显示系统托盘并进入“快速应用程序切换模式”,您的应用程序向上滑动以显示其他正在运行的应用程序,并且您的应用程序将进入非事件状态(即使它仍然大部分可见)。如果您在此模式下收到推送通知,您的应用委托(delegate)将收到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 之前执行此操作。我选择将它们作为本地通知发送

-(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;
}

关于iOS:推送通知、UIApplicationStateInactive 和快速应用切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18707210/

相关文章:

android - Firebase notification_key 发送通知

ios - 如何在不注册远程静默通知的情况下获取要使用的推送 token ?

objective-c - 在 debian (Apache) 后台运行 php 脚本

iphone - 我应该什么时候释放 [[UIApplication sharedApplication] delegate] 对象?

iphone - 当我的应用收到重大位置更改时,会调用哪些 UIApplicationDelegate 方法?

ios - 解包可选值“”时,prepareForSegue “” 意外发现 nil 错误

ios - iOS 中的摄像头运动感应

ios - 私有(private) iOS 应用

android - 带有图像的可扩展字符串不适用于推送通知

iOS 深度链接 + 如果未安装应用程序则重定向到 App Store