我正在尝试在后台接收推送通知,但它似乎不起作用。 这是我的AppDelegate代码:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
GCMService.sharedInstance().appDidReceiveMessage(userInfo);
var notification = UILocalNotification()
notification.alertBody = "Nova poruka od korisnika "+(userInfo["gcm.notification.username"] as! String) // text that will be displayed in the notification
notification.fireDate=NSDate(timeIntervalSinceNow: 0)
notification.applicationIconBadgeNumber=0
notification.soundName = UILocalNotificationDefaultSoundName // play default sound
notification.userInfo=userInfo // assign a unique identifier to the notification so that we can retrieve it later
notification.timeZone=NSTimeZone.localTimeZone()
UIApplication.sharedApplication().scheduleLocalNotification(notification)
completionHandler(UIBackgroundFetchResult.NoData)
}
当我在前台时,我收到了对此功能的回调,但是只要点击主页按钮,就不会收到通知(我猜测VPN部分失败了)。
这是发送通知的PHP代码:
(我知道这是可怕的代码,但我正在调试atm:P)
foreach ($iosIDs as $id) {
$fields = array("to" => $id, "notification" => $msg, "priority" => "high", "content_available" => true);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://gcm-http.googleapis.com/gcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
echo $result;
curl_close($ch);
}
我已经阅读了至少10个问题,但似乎无法弄明白。非常感谢。
答案 0 :(得分:1)
确保将"priority": "high"
添加到JSON。这样,您就可以在后台获取通知。
GCM尝试立即提供高优先级消息,允许GCM服务在可能的情况下唤醒休眠设备并打开与应用服务器的网络连接。例如,具有即时消息,聊天或语音呼叫警报的应用程序通常需要打开网络连接并确保GCM毫不拖延地将消息传递给设备。仅当消息对时间至关重要并且需要用户立即进行交互时才设置高优先级,并注意将消息设置为高优先级会导致电池消耗比普通优先级消息更多。
如果这没有帮助,我在此thread中发现您应该以适当的格式发送数据。样品:
{
"notification":{
"badge":"12",
"alert":"default",
"sound":"default",
"title":"default"
},
"content_available":true,
"to":"YOUR_KEY_HERE"
}
您还可以查看此link。