我试图在后台接收推送通知,但它似乎不工作。下面是我的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)
}
当我在前台时,我收到这个函数的回调,但是只要我点击home键,通知就没有收到(我猜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个,但似乎还是不明白。多谢。
确保将"priority": "high"
添加到JSON中。这样,你可以在后台获得通知。
GCM尝试立即传递高优先级消息,允许GCM服务在可能的情况下唤醒睡眠设备并打开与应用程序服务器的网络连接。例如,具有即时消息、聊天或语音呼叫提醒的应用程序通常需要打开网络连接,并确保GCM将消息无延迟地发送到设备。只有当消息是时间关键且需要用户立即交互时才设置高优先级,并且要注意,将消息设置为高优先级与正常优先级消息相比,会导致更多的电池消耗。
如果这没有帮助,我在这个线程中发现你应该以适当的格式发送数据。示例:
{
"notification":{
"badge":"12",
"alert":"default",
"sound":"default",
"title":"default"
},
"content_available":true,
"to":"YOUR_KEY_HERE"
}