在iOS中,当应用程序处于后台模式时,GCM通知不会收到 [英] GCM Notifications not receiving when app is in background mode in iOS

查看:211
本文介绍了在iOS中,当应用程序处于后台模式时,GCM通知不会收到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在现有的应用程序中配置了GCM,并且在那里接收通知。现在我面临两个问题:
1)我没有收到通知当我退出应用程序或应用程序在后台。
2)我没有收到iphone通知区域的通知,只有当我的应用程序正在运行时,我才直接收到警报消息。并且,当我拉下通知区域时,我在xcode的控制台中收到此消息无法连接到GCM:操作无法完成(com.google.gcm error 2001。)



我的PHP文件低于

 <?php 

//你要发送到iOS设备的有效载荷数据
//(可通过意向附加功能访问)
$ data = array('message'=>'Hello World! );

//此通知的收件人注册代币
// http://developer.android.com/google/gcm/
$ ids = array('kucy6xoUmx ** ****** eeRsla');

//发送GCM推送
sendGoogleCloudMessage($ data,$ ids);

函数sendGoogleCloudMessage($ data,$ ids)
{
//从Google API控制台插入真正的GCM API密钥
// https://code.google .com / apis / console /
$ apiKey ='AIz ****** 9JA';

//定义到GCM端点的URL
$ url ='https://gcm-http.googleapis.com/gcm/send';

//设置GCM发布变量(设备ID和推送有效负载)
$ post = array(
'registration_ids'=> $ ids,
'data' => $ data,
);

//设置CURL请求头(认证和类型)
$ headers = array(
'Authorization:key ='。$ apiKey,
'Content-Type :application / json'
);

//初始化curl句柄
$ ch = curl_init();

//将URL设置为GCM端点
curl_setopt($ ch,CURLOPT_URL,$ url);

//将请求方法设置为POST
curl_setopt($ ch,CURLOPT_POST,true);

//设置我们的自定义头文件
curl_setopt($ ch,CURLOPT_HTTPHEADER,$ headers);

//以字符串形式获取响应,而不是打印它
curl_setopt($ ch,CURLOPT_RETURNTRANSFER,true);

//设置JSON发布数据
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);

//调试GCM响应
echo $ result;
}

?>

这是我的AppDelegate.m文件



<$ $($ BOOT)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// [ START_EXCLUDE]
_registrationKey = @onRegistrationCompleted;
_messageKey = @onMessageReceived;
//配置Google上下文:解析GoogleService-Info.plist,并初始化
//在文件中有条目的服务
NSError * configureError;
[[GGLContext sharedInstance] configureWithError:& configureError];
NSAssert(!configureError,@配置Google服务时出错:%@,configureError);
_gcmSenderID = [[[GGLContext sharedInstance]配置] gcmSenderID];
//注册远程通知
if(floor(NSFoundationVersionNumber)< = NSFoundationVersionNumber_iOS_7_1){
// iOS 7.1或更早版本
UIRemoteNotificationType allNotificationTypes =
(UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge);
[application registerForRemoteNotificationTypes:allNotificationTypes];
} else {
// iOS 8或更高版本
// [END_EXCLUDE]
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *设置=
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
// [END register_for_remote_notifications]
// [START start_gcm_service]
GCMConfig * gcmConfig = [GCMConfig defaultConfig];
gcmConfig.receiverDelegate = self;
[[GCMService sharedInstance] startWithConfig:gcmConfig];
// [END start_gcm_service]
__weak typeof(self)weakSelf = self;
//处理注册令牌请求
_registrationHandler = ^(NSString * registrationToken,NSError * error){
if(registrationToken!= nil){
weakSelf.registrationToken = registrationToken;
NSLog(@注册令牌:%@,registrationToken);
[weakSelf subscribeToTopic];
NSDictionary * userInfo = @ {@registrationToken:registrationToken};
[[NSNotificationCenter defaultCenter] postNotificationName:weakSelf.registrationKey
object:nil
userInfo:userInfo];
} else {
NSLog(@GCM注​​册失败,错误:%@,error.localizedDescription);
NSDictionary * userInfo = @ {@error:error.localizedDescription};
[[NSNotificationCenter defaultCenter] postNotificationName:weakSelf.registrationKey
object:nil
userInfo:userInfo];
}
};
返回YES;

$ b - (void)subscribeToTopic {
//如果应用程序具有注册令牌并连接到GCM,请继续订阅
//主题
if(_registrationToken& amp;& _connectedToGCM){
[[GCMPubSub sharedInstance] subscribeWithToken:_registrationToken
topic:SubscriptionTopic
options:nil
handler:^(NSError *错误){
if(error){
//更加温和地处理已订阅错误
if(error.code == 3001){
NSLog(@Already订阅%@,
SubscriptionTopic);
} else {
NSLog(@订阅失败:%@,
error.localizedDescription);
}
} else {
self.subscribedToTopic = true;
NSLog(@订阅%@,SubscriptionTopic);
}
}];


$ b $ // [START connect_gcm_service]
- (void)applicationDidBecomeActive:(UIApplication *)application {
//连接到GCM服务器接收非APNS通知
[[GCMService sharedInstance] connectWithHandler:^(NSError * error){
if(error){
NSLog(@无法连接到GCM:%@ ,error.localizedDescription);
} else {
_connectedToGCM = true;
NSLog(@连接到GCM);
// [START_EXCLUDE]
[self subscribeToTopic];
// [END_EXCLUDE]
}
}];

// [END connect_gcm_service]

[START disconnect_gcm_service]
- (void)applicationDidEnterBackground:(UIApplication *)application {
[ [GCMService sharedInstance] disconnect];
// [START_EXCLUDE]
_connectedToGCM = NO;
// [END_EXCLUDE]
}
// [END disconnect_gcm_service]

// [START receive_apns_token]
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
// [END receive_apns_token]
// [START get_gcm_reg_token]
//创建一个配置并设置一个实现的委托GGLInstaceIDDelegate协议。
GGLInstanceIDConfig * instanceIDConfig = [GGLInstanceIDConfig defaultConfig];
instanceIDConfig.delegate = self;
//使用该配置启动GGLInstanceID共享实例,并请求注册
//令牌以启用接收通知
[[GGLInstanceID sharedInstance] startWithConfig:instanceIDConfig];
_registrationOptions = @ {kGGLInstanceIDRegisterAPNSOption:deviceToken,
kGGLInstanceIDAPNSServerTypeSandboxOption:@NO};
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:_gcmSenderID
scope:kGGLInstanceIDScopeGCM
options:_registrationOptions
handler:_registrationHandler];
// [END get_gcm_reg_token]
}

[START receive_apns_token_error]
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError: (NSError *)错误{
NSLog(@远程通知注册失败,错误:%@,error.localizedDescription);
// [END receive_apns_token_error]
NSDictionary * userInfo = @ {@error:error.localizedDescription};
[[NSNotificationCenter defaultCenter] postNotificationName:_registrationKey
object:nil
userInfo:userInfo];


[START ack_message_reception]
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(@收到通知:%@,userInfo);
//这只在应用程序启动GCM服务时有效
[[GCMService sharedInstance] appDidReceiveMessage:userInfo];
//处理收到的消息
// [START_EXCLUDE]
[[NSNotificationCenter defaultCenter] postNotificationName:_messageKey
object:nil
userInfo:userInfo];
// [END_EXCLUDE]

$ b - (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler: (void(^)(UIBackgroundFetchResult))handler {
NSLog(@Notification received:%@,userInfo);
//这只在应用程序启动GCM服务时有效
[[GCMService sharedInstance] appDidReceiveMessage:userInfo];
//处理收到的消息
//调用完成处理程序,传递相应的UIBackgroundFetchResult值
// [START_EXCLUDE]
[[NSNotificationCenter defaultCenter] postNotificationName:_messageKey
object:nil
userInfo:userInfo];
处理程序(UIBackgroundFetchResultNoData);
// [END_EXCLUDE]
}
// [END ack_message_reception]

// [START on_token_refresh]
- (void)onTokenRefresh {
//注册令牌轮换正在发生,所以应用程序需要请求一个新的令牌。
NSLog(@需要更改GCM注册标记。);
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:_gcmSenderID
scope:kGGLInstanceIDScopeGCM
options:_registrationOptions
handler:_registrationHandler];

// [END on_token_refresh]

// [START upstream_callbacks]
- (void)willSendDataMessageWithID:(NSString *)messageID错误:(NSError *)错误{
if(error){
//发送消息失败。
} else {
//将发送消息,您可以保存消息ID以跟踪消息
}
}

- (void)didSendDataMessageWithID: (NSString *)messageID {
//成功发送messageID标识的消息
}
// [END upstream_callbacks]

- (void)didDeleteMessagesOnServer {
//在接收之前,发送到此设备的一些消息在GCM服务器上被删除,可能是
//因为TTL已过期。客户端应该通知应用程序服务器,以便应用程序
//服务器可以重新发送这些消息。
}

我不是PHP脚本高手,请帮助我解决问题我的问题。

解决方案

我已经添加了

 'content_available'=> true,//在iOS应用程序处于后台时触发
'priority'=> '高',
'通知'=> $ data,
$ data = array('message'=>'Hello World!','body'=>'Hello World!');

添加到您的代码中。
请尝试下面的代码;

 <?php 

// Payload data you想要发送给iOS设备
//(可通过意向附加设备访问)
$ data = array('message'=>'Hello World!','body'=> '你好,世界!');

//此通知的收件人注册代币
// http://developer.android.com/google/gcm/
$ ids = array('kucy6xoUmx ** ****** eeRsla');

//发送GCM推送
sendGoogleCloudMessage($ data,$ ids);

函数sendGoogleCloudMessage($ data,$ ids)
{
//从Google API控制台插入真正的GCM API密钥
// https://code.google .com / apis / console /
$ apiKey ='AIz ****** 9JA';

//定义到GCM端点的URL
$ url ='https://gcm-http.googleapis.com/gcm/send';

//设置GCM发布变量(设备ID和推送有效负载)
$ post = array(
'registration_ids'=> $ ids,
'data' => $ data,
'content_available'=> true,
'priority'=>'high',
'notification'=> $ data,
) ;

//设置CURL请求头(认证和类型)
$ headers = array(
'Authorization:key ='。$ apiKey,
'Content-Type :application / json'
);

//初始化curl句柄
$ ch = curl_init();

//将URL设置为GCM端点
curl_setopt($ ch,CURLOPT_URL,$ url);

//将请求方法设置为POST
curl_setopt($ ch,CURLOPT_POST,true);

//设置我们的自定义头文件
curl_setopt($ ch,CURLOPT_HTTPHEADER,$ headers);

//以字符串形式获取响应,而不是打印它
curl_setopt($ ch,CURLOPT_RETURNTRANSFER,true);

//设置JSON发布数据
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);

//调试GCM响应
echo $ result;
}

?>

在IOS方面;
遵循 GCM网站上的订单



编辑1:
您可以尝试发送ios通知; 我修改了上面的php代码;
变更是;

'notification'=> $ data,


$ b

$ data = array('message'=>'Hello World!','body'=>'Hello World!');

I have configured GCM in my existing app and i am receiving the notifications there. Now i am facing two problem: 1) I am not receiving notifications When i exit the application or application is in the background. 2) I am not receiving notification in iphone's notification area, only when my app is running i only direct receive alert message there. And when i pull down notification area i get this message in xcode's console "Could not connect to GCM: The operation couldn’t be completed. (com.google.gcm error 2001.)"

My PHP file is below

<?php

// Payload data you want to send to iOSdevice(s)
// (it will be accessible via intent extras)    
$data = array( 'message' => 'Hello World!');

// The recipient registration tokens for this notification
// http://developer.android.com/google/gcm/ 
$ids = array( 'kucy6xoUmx********eeRsla' );

// Send a GCM push
sendGoogleCloudMessage(  $data, $ids );

function sendGoogleCloudMessage( $data, $ids )
{
    // Insert real GCM API key from Google APIs Console
    // https://code.google.com/apis/console/        
    $apiKey = 'AIz******9JA';

    // Define URL to GCM endpoint
    $url = 'https://gcm-http.googleapis.com/gcm/send';

    // Set GCM post variables (device IDs and push payload)     
    $post = array(
                    'registration_ids'  => $ids,
                    'data'              => $data,                   
                    );

    // Set CURL request headers (authentication and type)       
    $headers = array( 
                        'Authorization: key=' . $apiKey,
                        'Content-Type: application/json'
                    );

    // Initialize curl handle       
    $ch = curl_init();

    // Set URL to GCM endpoint      
    curl_setopt( $ch, CURLOPT_URL, $url );

    // Set request method to POST       
    curl_setopt( $ch, CURLOPT_POST, true );

    // Set our custom headers       
    curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );

    // Get the response back as string instead of printing it       
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

    // Set JSON post data
    curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $post ) );

    // Actually send the push   
    $result = curl_exec( $ch );

    // Error handling
    if ( curl_errno( $ch ) )
    {
        echo 'GCM error: ' . curl_error( $ch );
    }

    // Close curl handle
    curl_close( $ch );

    // Debug GCM response       
    echo $result;
}

?>

Here is my AppDelegate.m file

// [START register_for_remote_notifications]
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // [START_EXCLUDE]
    _registrationKey = @"onRegistrationCompleted";
    _messageKey = @"onMessageReceived";
    // Configure the Google context: parses the GoogleService-Info.plist, and initializes
    // the services that have entries in the file
    NSError* configureError;
    [[GGLContext sharedInstance] configureWithError:&configureError];
    NSAssert(!configureError, @"Error configuring Google services: %@", configureError);
    _gcmSenderID = [[[GGLContext sharedInstance] configuration] gcmSenderID];
    // Register for remote notifications
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
        // iOS 7.1 or earlier
        UIRemoteNotificationType allNotificationTypes =
        (UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge);
        [application registerForRemoteNotificationTypes:allNotificationTypes];
    } else {
        // iOS 8 or later
        // [END_EXCLUDE]
        UIUserNotificationType allNotificationTypes =
        (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings =
        [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    // [END register_for_remote_notifications]
    // [START start_gcm_service]
    GCMConfig *gcmConfig = [GCMConfig defaultConfig];
    gcmConfig.receiverDelegate = self;
    [[GCMService sharedInstance] startWithConfig:gcmConfig];
    // [END start_gcm_service]
    __weak typeof(self) weakSelf = self;
    // Handler for registration token request
    _registrationHandler = ^(NSString *registrationToken, NSError *error){
        if (registrationToken != nil) {
            weakSelf.registrationToken = registrationToken;
            NSLog(@"Registration Token: %@", registrationToken);
            [weakSelf subscribeToTopic];
            NSDictionary *userInfo = @{@"registrationToken":registrationToken};
            [[NSNotificationCenter defaultCenter] postNotificationName:weakSelf.registrationKey
                                                                object:nil
                                                              userInfo:userInfo];
        } else {
            NSLog(@"Registration to GCM failed with error: %@", error.localizedDescription);
            NSDictionary *userInfo = @{@"error":error.localizedDescription};
            [[NSNotificationCenter defaultCenter] postNotificationName:weakSelf.registrationKey
                                                                object:nil
                                                              userInfo:userInfo];
        }
    };
    return YES;
}

- (void)subscribeToTopic {
    // If the app has a registration token and is connected to GCM, proceed to subscribe to the
    // topic
    if (_registrationToken && _connectedToGCM) {
        [[GCMPubSub sharedInstance] subscribeWithToken:_registrationToken
                                                 topic:SubscriptionTopic
                                               options:nil
                                               handler:^(NSError *error) {
                                                   if (error) {
                                                       // Treat the "already subscribed" error more gently
                                                       if (error.code == 3001) {
                                                           NSLog(@"Already subscribed to %@",
                                                                 SubscriptionTopic);
                                                       } else {
                                                           NSLog(@"Subscription failed: %@",
                                                                 error.localizedDescription);
                                                       }
                                                   } else {
                                                       self.subscribedToTopic = true;
                                                       NSLog(@"Subscribed to %@", SubscriptionTopic);
                                                   }
                                               }];
    }
}

// [START connect_gcm_service]
- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Connect to the GCM server to receive non-APNS notifications
    [[GCMService sharedInstance] connectWithHandler:^(NSError *error) {
        if (error) {
            NSLog(@"Could not connect to GCM: %@", error.localizedDescription);
        } else {
            _connectedToGCM = true;
            NSLog(@"Connected to GCM");
            // [START_EXCLUDE]
            [self subscribeToTopic];
            // [END_EXCLUDE]
        }
    }];
}
// [END connect_gcm_service]

// [START disconnect_gcm_service]
- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[GCMService sharedInstance] disconnect];
    // [START_EXCLUDE]
    _connectedToGCM = NO;
    // [END_EXCLUDE]
}
// [END disconnect_gcm_service]

// [START receive_apns_token]
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // [END receive_apns_token]
    // [START get_gcm_reg_token]
    // Create a config and set a delegate that implements the GGLInstaceIDDelegate protocol.
    GGLInstanceIDConfig *instanceIDConfig = [GGLInstanceIDConfig defaultConfig];
    instanceIDConfig.delegate = self;
    // Start the GGLInstanceID shared instance with the that config and request a registration
    // token to enable reception of notifications
    [[GGLInstanceID sharedInstance] startWithConfig:instanceIDConfig];
    _registrationOptions = @{kGGLInstanceIDRegisterAPNSOption:deviceToken,
                             kGGLInstanceIDAPNSServerTypeSandboxOption:@"NO"};
    [[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:_gcmSenderID
                                                        scope:kGGLInstanceIDScopeGCM
                                                      options:_registrationOptions
                                                      handler:_registrationHandler];
    // [END get_gcm_reg_token]
}

// [START receive_apns_token_error]
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Registration for remote notification failed with error: %@", error.localizedDescription);
    // [END receive_apns_token_error]
    NSDictionary *userInfo = @{@"error" :error.localizedDescription};
    [[NSNotificationCenter defaultCenter] postNotificationName:_registrationKey
                                                        object:nil
                                                      userInfo:userInfo];
}

// [START ack_message_reception]
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSLog(@"Notification received: %@", userInfo);
    // This works only if the app started the GCM service
    [[GCMService sharedInstance] appDidReceiveMessage:userInfo];
    // Handle the received message
    // [START_EXCLUDE]
    [[NSNotificationCenter defaultCenter] postNotificationName:_messageKey
                                                        object:nil
                                                      userInfo:userInfo];
    // [END_EXCLUDE]
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
    NSLog(@"Notification received: %@", userInfo);
    // This works only if the app started the GCM service
    [[GCMService sharedInstance] appDidReceiveMessage:userInfo];
    // Handle the received message
    // Invoke the completion handler passing the appropriate UIBackgroundFetchResult value
    // [START_EXCLUDE]
    [[NSNotificationCenter defaultCenter] postNotificationName:_messageKey
                                                        object:nil
                                                      userInfo:userInfo];
    handler(UIBackgroundFetchResultNoData);
    // [END_EXCLUDE]
}
// [END ack_message_reception]

// [START on_token_refresh]
- (void)onTokenRefresh {
    // A rotation of the registration tokens is happening, so the app needs to request a new token.
    NSLog(@"The GCM registration token needs to be changed.");
    [[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:_gcmSenderID
                                                        scope:kGGLInstanceIDScopeGCM
                                                      options:_registrationOptions
                                                      handler:_registrationHandler];
}
// [END on_token_refresh]

// [START upstream_callbacks]
- (void)willSendDataMessageWithID:(NSString *)messageID error:(NSError *)error {
    if (error) {
        // Failed to send the message.
    } else {
        // Will send message, you can save the messageID to track the message
    }
}

- (void)didSendDataMessageWithID:(NSString *)messageID {
    // Did successfully send message identified by messageID
}
// [END upstream_callbacks]

- (void)didDeleteMessagesOnServer {
    // Some messages sent to this device were deleted on the GCM server before reception, likely
    // because the TTL expired. The client should notify the app server of this, so that the app
    // server can resend those messages.
}

I am not a php script master so please help me that how i can resolve my issues.

解决方案

I have added

 'content_available' => true,//to trigger when iOS app is in background
 'priority' => 'high',
 'notification' => $data,
 $data = array( 'message' => 'Hello World!', 'body' => 'Hello World!');

to your code. Please try below code;

<?php

// Payload data you want to send to iOSdevice(s)
// (it will be accessible via intent extras)    
$data = array( 'message' => 'Hello World!', 'body' => 'Hello World!');

// The recipient registration tokens for this notification
// http://developer.android.com/google/gcm/ 
$ids = array( 'kucy6xoUmx********eeRsla' );

// Send a GCM push
sendGoogleCloudMessage(  $data, $ids );

function sendGoogleCloudMessage( $data, $ids )
{
    // Insert real GCM API key from Google APIs Console
    // https://code.google.com/apis/console/        
    $apiKey = 'AIz******9JA';

    // Define URL to GCM endpoint
    $url = 'https://gcm-http.googleapis.com/gcm/send';

    // Set GCM post variables (device IDs and push payload)     
    $post = array(
                    'registration_ids'  => $ids,
                    'data'              => $data, 
                    'content_available'    => true,                 
                    'priority'              => 'high',    
                    'notification' => $data,               
                    );

    // Set CURL request headers (authentication and type)       
    $headers = array( 
                        'Authorization: key=' . $apiKey,
                        'Content-Type: application/json'
                    );

    // Initialize curl handle       
    $ch = curl_init();

    // Set URL to GCM endpoint      
    curl_setopt( $ch, CURLOPT_URL, $url );

    // Set request method to POST       
    curl_setopt( $ch, CURLOPT_POST, true );

    // Set our custom headers       
    curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );

    // Get the response back as string instead of printing it       
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

    // Set JSON post data
    curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $post ) );

    // Actually send the push   
    $result = curl_exec( $ch );

    // Error handling
    if ( curl_errno( $ch ) )
    {
        echo 'GCM error: ' . curl_error( $ch );
    }

    // Close curl handle
    curl_close( $ch );

    // Debug GCM response       
    echo $result;
}

?>

on IOS side; Follow orders on GCM Site

EDIT 1: You may try sending notification for ios;

I edited your php code above; Changes are;

'notification' => $data,

and

$data = array( 'message' => 'Hello World!', 'body' => 'Hello World!');

这篇关于在iOS中,当应用程序处于后台模式时,GCM通知不会收到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆