如何在锁定屏幕通知中心显示之前拦截iOS推送通知?

时间:2015-07-24 18:25:33

标签: ios objective-c notifications push-notification google-cloud-messaging

我正致力于将应用与GCM集成,以便获得简单的全局主题推送通知。与GCM通信的服务器端是用Java / Spring编写的,并且大部分都按预期工作。但是,我在iOS方面可能无法解决问题。

理想情况下,我不想将推送通知作为带有消息的扁平字符串,而是希望通过一些JSON结构(以字符串格式)发送带有一些元数据的元数据,就像显示通知一样,我打算将其保留在应用程序的其他地方进行审核。

现在,当应用程序处于活动状态时,我没有任何问题,因为我的应用代理运行

- (void)application:(UIApplication *)application
    didReceiveRemoteNotification:(NSDictionary *)userInfo 
    fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
    ....
}

通过我的主viewController中的通知注册,很高兴地将远程通知传递给我的viewController代码,在那里我可以解析JSON并按照我的方式去做。

然而,我似乎无法找到一个类似的方法/程序,我可以定义它给予我与应用程序不在前台时进来的通知相同的控制。这导致锁屏推送通知以字符串格式显示我的JSON结构,显然不是我想要的。

现在,从技术上讲,我可以简单地推送消息,并使用消息字符串本身作为唯一键来手动访问我的数据库以获取元数据,但我想避免这种情况有两个原因。一,似乎浪费时间/资源,但有两个,我喜欢在通知的客户端控制一些。我在不同的设备上遇到问题(iPad 2与iPhone 5s),我的代码会显示重复的推送通知,也就是说,iPad获取推送并显示一次,iPhone似乎会收到两次。我很担心我误解了

的用法
    UIUserNotificationType allNotificationTypes =
    (UIUserNotificationTypeAlert);
    UIUserNotificationSettings *settings =
    [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];


    [[GCMService sharedInstance] startWithConfig:[GCMConfig defaultConfig]];

这些线条以及它们如何影响锁定屏幕上显示的内容,但是如果可以确保重复项永远不会显示,我仍然宁愿进行手动控制。

1 个答案:

答案 0 :(得分:1)

您可以通过通知发送任何您想要的内容,iOS设备会将其作为必需的一些值,如果您发送以下消息,您可以显示一些消息并通过通知发送其他数据,想象一下这个基本通知:

{
  aps: {
    alert: "Hi there"
  }
}

此通知将在锁定屏幕和设备上的通知栏中显示警告消息,但也可以发送此消息:

{
  aps: {
    alert: "Hi there",
    content-available: 1, // Add this if you want background processing
    sound: "" // If you don't want to show the notification on the notification area nor the lock screen.
  }
  data: {
    effectiveTime: ...,
    expirationTime: ...,
    message: ...,
    ...
  }
}

这将在您的设备上显示与第一个完全相同的通知,但在这种情况下,您可以使用didReceiveRemoteNotification:方法对数据执行任何操作

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  NSLog(@"My data sent trough GCM: %@", userInfo[@"data"]);
}

您可以使用的唯一密钥是the official push notifications docs

中3-1和3-2中列出的密钥

如果你想管理后台处理,根据to the docs你应该使用(如你所说)application:didReceiveRemoteNotification:fetchCompletionHandler:,但其他一切都保持不变:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler {

  switch (application.applicationState) { 
    case UIApplicationStateInactive:
      // Do whatever you want if the app is inactive
      handler(UIBackgroundFetchResultNewData);
      break;

    case UIApplicationStateBackground:
      // Do whatever you want if the app is in background
      handler(UIBackgroundFetchResultNewData);
      break;

    case default:
      // Do whatever you want if the app is active
      handler(UIBackgroundFetchResultNewData);
      break;
  }
}