首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GCM和Swift在iphone上不显示

GCM和Swift在iphone上不显示
EN

Stack Overflow用户
提问于 2015-11-11 21:45:08
回答 2查看 428关注 0票数 1

我一直在关注google GCM教程中的推送通知。除了在屏幕上显示通知之外,一切似乎都正常。在xcode输出上,它显示信息已经发送。有没有人能帮帮我?我已经包括了php和swift.app。

Appdelegate.swift

代码语言:javascript
复制
  {

  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

代码语言:javascript
复制
<?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);


?>

我的输出结果如下:"results":{"message_id":"0:144724xxxxxx3ef9fd7ecd"}}:{"multicast_id":81418xxxxxx136054,“成功”:1,“失败”:0,"canonical_ids":0,php

xcode输出视图

收到通知:发件人: 76c1241cc5,徽章: 12,价格:测试,标题:默认,collapse_key: do_not_collapse,声音:默认,内容可用: true,正文: helloworld,优先级:高

所以,我只是有一个空白屏幕,没有任何通知,请让我知道我哪里出错了,谢谢

EN

回答 2

Stack Overflow用户

发布于 2015-11-13 00:24:49

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

更改此设置:

代码语言:javascript
复制
$fields = array(
        'registration_ids'  => array( $reg_id ),
        'data'              => array( 'price' => $message, 'sound' => 'default', 'body' => 'helloworld', 'title' => 'default', 'badge' => 12, 'content-available' => 'true', 'priority'=> 'high'),


    );

要这样做:

代码语言:javascript
复制
$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 )
    );
票数 1
EN

Stack Overflow用户

发布于 2015-11-12 13:40:36

这不是一种解决方案,而是一种更好的故障排除方法。我强烈建议安装一个名为Advanced REST Client的Google Chrome扩展:

Advanced REST Client Extention

有了它,你可以很容易地发送通知。我的理论是您的有效负载设置不正确。我遇到了完全相同的问题,我所要做的就是在有效负载中引入“优先级”:“高”。我知道你有它,但我只是担心它的格式不正确。尝试扩展,并尝试遵循我的格式。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33651882

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档