iOS 应用程序在后台时的 GCM 推送通知

GCM push notification when iOS app is in the background

我正在尝试使用 GCM 向我的 iOS 应用程序发送推送通知。该应用程序在后台时不会收到通知,但在前台时会收到通知。我正在使用 PHP 脚本测试推送通知,该脚本还将消息直接发送到 APNS 并且它在后台工作。

发送到 GCM 的 JSON:(我从休息客户端发送它用于测试)

{
  "to" : "token...",
  "notification" : {
    "title": "GCM TITLE",
    "body" : "FROM GCM",
    "badge": "1",
    "sound": "default"
  }
}

不工作: 在 didReceiveRemoteNotification 中从 GCM 收到的 userInfo:

Notification received: [aps: {
    alert =     {
        body = "FROM GCM";
        title = "GCM TILE";
    };
    badge = 1;
    sound = default;
}, gcm.message_id: 123...]

工作: 从 PHP 脚本发送时收到的 userInfo(我还将 message_id 添加到 JSON 以查看是否是问题所在)

Notification received: [aps: {
    alert =     {
        body = "FROM PHP";
        title = "PHP TITLE";
    };
    badge = 2;
    sound = default;
}, gcm.message_id: 123...]

我尝试用不同的组合将 content_available 添加到 JSON 但没有帮助,Content-Type 和授权请求 headers 也已设置:

Content-Type:application/json
Authorization:key=... 

如果有人遇到同样的问题,我的解决方案是将 "priority": "high" 添加到 JSON。这样我就可以在后台收到通知。

{
  "to" : "token...",
  "priority": "high",
  "notification" : {
    "title": "GCM TITLE",
    "body" : "FROM GCM",
    "badge": "1",
    "sound": "default"
  }
}

要在应用程序处于后台时收到通知,我注意到我们需要添加:

"content_available":true // when app in background
"priority":"high" //when app is completely closed not even running in background

 // "content_available":true  ..most important field 

{
"to" : "token...",
 "priority":"high",
 "content_available":true,
 "notification" : {
 "title": "GCM TITLE",
 "body" : "FROM GCM",
 "badge": "1",
 "sound": "default"
  }
}