上游消息 - iOS GCM

Upstream message - iOS GCM

我正在尝试使用 Xamarin API 在我的应用程序和服务器中实现 Google 消息传递。下游消息(服务器到应用程序)运行良好,但我无法让上游工作。

在服务器端,我将 PHP 与 XMPP 库 (JAXL) 一起使用,这样我就可以在 GCM 服务器上进行身份验证并将消息发送到设备。我已使用此代码注册接收消息:

$XMPPClient->add_cb("on__message", function($stanza){ 

        echo "new message";
        $data = json_decode(html_entity_decode($stanza->childrens[0] -> text), true);
        $messageType = $data['message_type'];
        $messageId = $data['message_id']; //message id which was sent by us
        $gcmKey = $data['from']; //gcm key;
        ...
        });

在客户端,我正在使用 GCM api 调用 SendMessage:

    public class SendClass : ReceiverDelegate
{
    public void SendMessage(string Message)
    {
        InstanceId.SharedInstance.Start(Google.InstanceID.Config.DefaultConfig);

        Service.SharedInstance.SendMessage(new NSDictionary("key", "value"), @"SenderID@gcm.googleapis.com", "Message");
    }

    public override void DidSendDataMessage(string messageID)
    {
        base.DidSendDataMessage(messageID);
    }

    public override void WillSendDataMessage(string messageID, NSError error)
    {
        base.WillSendDataMessage(messageID, error);
    }
}

GCM API 有两个方法应该在消息发送到服务器的过程中调用,DidSendDataMessageWillSendDataMessage,但是没有调用这些方法。

有人可以给我一些提示吗?

谢谢!

我发现了问题。 首先,您需要将 GoogleMessanging.Config 的 de delegate 设置为您的 class(继承自 ReceiverDelegate),注意不是来自GoogleInstanceID.Config.

之后需要调用Start()这两个库的方法,GoogleMessaging.ServiceGoogle.InstanceID。然后魔术就完成了:

        private void StartService()
    {
        NSError ConfigError;
        Google.Core.Context.SharedInstance.Configure(out ConfigError);
        GCMSenderID = Google.Core.Context.SharedInstance.Configuration.GcmSenderID;

        SendC = new SendClass();
        Google.GoogleCloudMessaging.Config Conf = Google.GoogleCloudMessaging.Config.DefaultConfig;
        Conf.ReceiverDelegate = SendC;

        Service.SharedInstance.Start(Conf);
        Service.SharedInstance.Connect(delegate (NSError error)
        {
            if (error == null)
            {
                GetToken();
            }
        });
    }

    private void GetToken()
    {
        InstanceId.SharedInstance.Start(Google.InstanceID.Config.DefaultConfig);
        InstanceId.SharedInstance.Token(GCMSenderID, Constants.ScopeGCM, new NSDictionary(Constants.RegisterAPNSOption, DevToken,
            Constants.APNSServerTypeSandboxOption, 1), delegate (string Token, NSError error)
            {
                if (Token != null)
                {
                    OnTokenReceived(Token);
                }
            });
    }