I'm working on getting background notifications to work on IOS with GCM - non-background notifications are already working. Here are my steps to integrate background notifications:
Here is the code for the delegate function:
func application( application: UIApplication,
didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
println("Notification received2: \(userInfo)")
GCMService.sharedInstance().appDidReceiveMessage(userInfo);
NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
userInfo: userInfo)
handler(UIBackgroundFetchResult.NoData);
}
This is the code for the on-server php script:
<?php
$regId = $_GET["regId"];
$message = $_GET["message"];
$data = array( 'price' => $message, 'sound' => 'default', 'body' => 'helloworld', 'title' => 'default', 'badge' => 12, 'content-available' => 1);
$ids = array( $regId);
sendGoogleCloudMessage( $data, $ids );
function sendGoogleCloudMessage( $data, $ids )
{
$apiKey = THE-API-KEY-THAT-I-AM-USING;
$url = 'https://android.googleapis.com/gcm/send';
$post = array(
'registration_ids' => $ids,
'data' => $data,
'content-available' => 1,
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $post ) );
$result = curl_exec( $ch );
if ( curl_errno( $ch ) )
{
echo 'GCM error: ' . curl_error( $ch );
}
curl_close( $ch );
echo $result;
}
?>
I have tried sending the content-available flag through both the inner "data" array and the outer "post" array, which I have indicated by adding it to both.
The message is not received by the fetchCompletionHandler function, but rather waits until the app is active again and is received by the normal application:didRecieveRemoteNotification function. What could be the reason that my notification is not received via the background functionality?
You should provide content_available to GCM, not content-available (like in APNs) and you will be able to receive push notifications in background.
https://developers.google.com/cloud-messaging/server-ref#send-downstream
PS - Less then five minutes ago I had absolutely same problem. We should read docs more carefully...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.