当前位置: 首页 > 知识库问答 >
问题:

GCM

霍鸣
2023-03-14

我一直在关注GoogleGCM的推送通知教程。除了屏幕上显示的通知外,其他一切似乎都正常工作。在xcode输出上,它显示已发送的信息。请给我一些帮助,我已经包括了php和swift.app

Appdelegate.swift

  {

  import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GGLInstanceIDDelegate, GCMReceiverDelegate {

    var window: UIWindow?

    var connectedToGCM = false
    var subscribedToTopic = false
    var gcmSenderID: String?
    var registrationToken: String?
    var registrationOptions = [String: AnyObject]()

    let registrationKey = "onRegistrationCompleted"
    let messageKey = "onMessageReceived"
    let subscriptionTopic = "/topics/global"

    // [START register_for_remote_notifications]
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions:
        [NSObject: AnyObject]?) -> Bool {
            // [START_EXCLUDE]
            // Configure the Google context: parses the GoogleService-Info.plist, and initializes
            // the services that have entries in the file
            var configureError:NSError?
            GGLContext.sharedInstance().configureWithError(&configureError)
            assert(configureError == nil, "Error configuring Google services: \(configureError)")
            gcmSenderID = GGLContext.sharedInstance().configuration.gcmSenderID
            // [END_EXCLUDE]
            // Register for remote notifications
            if #available(iOS 8.0, *) {
                let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
                application.registerUserNotificationSettings(settings)
                application.registerForRemoteNotifications()
            } else {
                // Fallback
                let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
                application.registerForRemoteNotificationTypes(types)
            }

            // [END register_for_remote_notifications]
            // [START start_gcm_service]
            let gcmConfig = GCMConfig.defaultConfig()
            gcmConfig.receiverDelegate = self
            //GCMService.sharedInstance().startWithConfig(gcmConfig)

            GCMService.sharedInstance().startWithConfig(GCMConfig.defaultConfig())
            // [END start_gcm_service]
            return true
    }




    func subscribeToTopic() {
        // If the app has a registration token and is connected to GCM, proceed to subscribe to the
        // topic
        if(registrationToken != nil && connectedToGCM) {
            GCMPubSub.sharedInstance().subscribeWithToken(self.registrationToken, topic: subscriptionTopic,
                options: nil, handler: {(NSError error) -> Void in
                    if (error != nil) {
                        // Treat the "already subscribed" error more gently
                        if error.code == 3001 {
                            print("Already subscribed to \(self.subscriptionTopic)")
                        } else {
                            print("Subscription failed: \(error.localizedDescription)");
                        }
                    } else {
                        self.subscribedToTopic = true;
                        NSLog("Subscribed to \(self.subscriptionTopic)");
                    }
            })
        }
    }

    // [START connect_gcm_service]
    func applicationDidBecomeActive( application: UIApplication) {
        GCMService.sharedInstance().connectWithHandler({
            (NSError error) -> Void in
            if error != nil {
                print("Could not connect to GCM: \(error.localizedDescription)")
            } else {
                print("Connected to GCM")
            }
        })
    }
    // [END connect_gcm_service]

    // [START disconnect_gcm_service]
    func applicationDidEnterBackground(application: UIApplication) {
        GCMService.sharedInstance().disconnect()
        // [START_EXCLUDE]
        self.connectedToGCM = true
        // [END_EXCLUDE]
    }
    // [END disconnect_gcm_service]

    // [START receive_apns_token]
    func application( application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken
        deviceToken: NSData ) {
            // [END receive_apns_token]
            // [START get_gcm_reg_token]
            // Create a config and set a delegate that implements the GGLInstaceIDDelegate protocol.
            let instanceIDConfig = GGLInstanceIDConfig.defaultConfig()
            instanceIDConfig.delegate = self
            // Start the GGLInstanceID shared instance with that config and request a registration
            // token to enable reception of notifications
            GGLInstanceID.sharedInstance().startWithConfig(instanceIDConfig)
            registrationOptions = [kGGLInstanceIDRegisterAPNSOption:deviceToken,
                kGGLInstanceIDAPNSServerTypeSandboxOption:true]
            GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID,
                scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler)
            // [END get_gcm_reg_token]
    }

    // [START receive_apns_token_error]
    func application( application: UIApplication, didFailToRegisterForRemoteNotificationsWithError
        error: NSError ) {
            print("Registration for remote notification failed with error: \(error.localizedDescription)")
            // [END receive_apns_token_error]
            let userInfo = ["error": error.localizedDescription]
            NSNotificationCenter.defaultCenter().postNotificationName(
                registrationKey, object: nil, userInfo: userInfo)
    }

    // [START ack_message_reception]
    func application( application: UIApplication,
        didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
            print("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]
    }

    func application( application: UIApplication,
        didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
        fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
            print("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(UIBackgroundFetchResult.NoData);
            // [END_EXCLUDE]
    }
    // [END ack_message_reception]

    func registrationHandler(registrationToken: String!, error: NSError!) {
        if (registrationToken != nil) {
            self.registrationToken = registrationToken
            print("Registration Token: \(registrationToken)")
            self.subscribeToTopic()
            let userInfo = ["registrationToken": registrationToken]
            NSNotificationCenter.defaultCenter().postNotificationName(
                self.registrationKey, object: nil, userInfo: userInfo)
        } else {
            print("Registration to GCM failed with error: \(error.localizedDescription)")
            let userInfo = ["error": error.localizedDescription]
            NSNotificationCenter.defaultCenter().postNotificationName(
                self.registrationKey, object: nil, userInfo: userInfo)
        }
    }

    // [START on_token_refresh]
    func onTokenRefresh() {
        // A rotation of the registration tokens is happening, so the app needs to request a new token.
        print("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]
    func willSendDataMessageWithID(messageID: String!, error: NSError!) {
        if (error != nil) {
            // Failed to send the message.
        } else {
            // Will send message, you can save the messageID to track the message
        }
    }

    func didSendDataMessageWithID(messageID: String!) {
        // Did successfully send message identified by messageID
    }
    // [END upstream_callbacks]

    func 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.
    }
   }

php

<?php


define("GOOGLE_API_KEY", "AIzaSyD5xxxxxxxxx4mp28rpU8Nw");
define("GOOGLE_GCM_URL", "https://gcm-http.googleapis.com/gcm/send");

//https://android.googleapis.com/gcm/send

function send_gcm_notify($reg_id, $message) {

 $message = "test";
    $fields = array(
        'registration_ids'  => array( $reg_id ),
        'data'              => array( 'price' => $message, 'sound' => 'default', 'body' => 'helloworld', 'title' => 'default', 'badge' => 12, 'content-available' => 'true', 'priority'=> 'high'),


    );



//$data = array( 'price' => $message, 'sound' => 'default', 'body' => 'helloworld', 'title' => 'default', 'badge' => 12, 'content-available' => 1);


    $headers = array(
        'Authorization: key=' . GOOGLE_API_KEY,
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, GOOGLE_GCM_URL);
    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);
    if ($result === FALSE) {
        die('Problem occurred: ' . curl_error($ch));
    }

    curl_close($ch);
    echo $result;
 }

$reg_id ="kiIp-2Q3en4:APA91bEaFJxxxxxxxxxLBNT8rDsyxyTmW97hiDQSouQI6nNC7JwUPBxzRmHpjx2BHQcvgEiaO0J4dS_2dHy2mfCoEgej3SevQFJ4eMMTUSgwvP634KMmK8vgy2DwtdxfvkBck";
$msg = "Google 123";

send_gcm_notify($reg_id, $msg);


?>

以下是我的输出结果:php:{“多播_id”:81418xxxxxx136054,“成功”:1,“失败”:0,“规范_id”:0,“结果”:[{“消息_id”:“0:144724xxxxx3ef9fd7ecd”}]

xcode输出视图

收到通知:[发件人:76C1241C5,徽章:12,价格:测试,标题:默认,折叠\u键:不折叠,声音:默认,可用内容:真,正文:helloworld,优先级:高]

所以,我只是有一个没有通知的空白屏幕,请让我知道我哪里出了问题,提前谢谢Hesh

共有1个答案

计燕七
2023-03-14

在iOS上,如果希望显示系统通知,则必须发送通知消息。在您的问题中,您正在发送一条数据消息,因此,如果您还想随消息发送数据,请尝试将通知有效负载作为“收件人”字段和“数据”字段的同级。

改变这个:

$fields = array(
        'registration_ids'  => array( $reg_id ),
        'data'              => array( 'price' => $message, 'sound' => 'default', 'body' => 'helloworld', 'title' => 'default', 'badge' => 12, 'content-available' => 'true', 'priority'=> 'high'),


    );

为此:

$fields = array(
        'registration_ids'  => array( $reg_id ),
        'priority'=> array( 'high' ),
        'content_available' => array( 'true' ),
        'data'              => array( 'price' => $message ),
        'notification'      => array( 'sound' => 'default', 'body' => 'helloworld', 'title' => 'default', 'badge' => 12 )
    );
 类似资料:
  • 问题内容: 我有一些AES / GCM加密数据,想对其解密。我想绕过身份验证解密它,因为数据不包含身份验证信息(数据由第三方应用程序加密)。我尝试使用javax.crypto包进行解密,但它始终会引发标签不匹配错误。有什么方法可以绕过此标签检查并解密数据。数据使用AES128加密,并且使用12字节初始化向量。 编辑:我得到了这个问题的临时解决方案。不知道这是否是正确的方法。 问题答案: 是的,可以

  • 问题内容: 据我所知,目前大多数android教程和示例都依赖于GCM的使用,以将数据从服务器发送到android设备。并使用php脚本和post / get方法将数据从设备发送到服务器。 我的一个朋友(对Android编程一无所知的人)只是问我,为什么我们不能在Java中使用Socket类?在传统的Java编程中,您使用套接字(IP地址+端口号)来实现类似于GCM的功能(单个服务器多个客户端-

  • 问题内容: 根据Java 7文档以及第三方供应商的说法,似乎Java 7应该支持AES-GCM套件: IBM Java 7 Java 7 SSL文档 在客户端和服务器之间的协商中遇到一些错误,由于仅将其限制为AES- GCM密码而无法协商密码。经过调查,我发现客户端或服务器(tomcat实例)均不支持密码套件。在客户端上运行一些示例代码以获取输出: 不知道是否有人遇到过这样的问题。 Java 7是

  • 问题内容: 我正在尝试在我的应用程序中工作(在工作时间变更或正在进行任何促销时通知用户),但是在尝试使用Google Cloud Messaging API时,我一直收到错误消息。 我正在使用新发布的Android Studio IDE对此进行编码。 这是我的GcmBroadcastReciever.java代码: 问题答案: 以下各节将指导您完成设置GCM实施的过程。开始之前,请确保设置Goog

  • 问题内容: 我正在写一个使用GCM消息的游戏。当一名玩家进入转牌移动到服务器时,服务器将向其对手发送一条GCM消息,让客户知道有其他转弯数据可用。这应该很简单。我尽可能地遵循了示例GCM客户代码。 我有两个要测试的设备:带有4.4.0冰淇淋三明治的Motorola Xoom带有2.3.5版姜饼的Motorola X2 两种设备都有Goggle帐户设置(实际上是同一帐户)。我可以从两者的Play商店

  • 问题内容: 我正打算实施GCM。我编写了一个测试代码以了解其工作原理,但在响应中不断出现错误400。 我正在用Java(JDK 7)编写。 在这个主题上,我遵循了这一原则。我在那里修改了给定的代码,并将ObjectMapper的用法更改为Gson。 这是我对数据对象的代码: *我在服务器参考中看到,在HTTP协议中,我可以只发送带有registration_ids的消息。(所有其他均为可选) 这是

  • 问题内容: 我已经使用GCM很长时间了。有一天,它突然破裂了。问题是我发送的第一个推送获得了成功状态,但该应用程序未收到任何推送。我发送的第二次推送失败,并显示NotRegistered错误。我重新安装该应用程序:成功(未收到通知),失败(未注册)->循环。我不知道发生了什么变化。Google支持非常无助,需要花费大量时间来回答简单的问题,无论是GCM问题,APNs问题还是客户问题。如果以前有人遇

  • 问题内容: 我想知道ECDHE-ECDSA-AES128-GCM-SHA256和ECDHE-ECDSA-AES128-GCM- SHA256是否有最低密钥生成要求?我正在尝试使用上述算法之一来获取TLS客户端和服务器,以使其彼此连接并继续接收“无共享密码错误”。我创建了一个用于签署客户端和服务器证书的CA,并尝试仅与openssl以及在node.js中进行连接。我正在localhost(127.0