Firebase Cloud Messaging and C# server side code

2019-05-05 18:05发布

问题:

I am using FCM in my Android and iOS app. The client side code is working correctly because from the Firebase console I can send notifications to both platforms with out any problem. With my C# code I can send notifications successfully to android devices but the notifications never appear on iPhone unless directly coming from the Firebase notification console. I don't know what gives.

C# server-side code

try
{
    var applicationID = "application_id";
    var senderId = "sender_id";
    string deviceId = "device_id_of_reciever";
    WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
    tRequest.Method = "post";
    tRequest.ContentType = "application/json";
    var data = new
    {
        to = deviceId,
        notification = new
        {
            body = "This is the message",
            title = "This is the title",
            icon = "myicon"
        }
    };

    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(data);
    Byte[] byteArray = Encoding.UTF8.GetBytes(json);
    tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
    tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
    tRequest.ContentLength = byteArray.Length;

    using (Stream dataStream = tRequest.GetRequestStream())
    {
        dataStream.Write(byteArray, 0, byteArray.Length);
        using (WebResponse tResponse = tRequest.GetResponse())
        {
            using (Stream dataStreamResponse = tResponse.GetResponseStream())
            using (StreamReader tReader = new StreamReader(dataStreamResponse))
            {
                String sResponseFromServer = tReader.ReadToEnd();
                Response.Write(sResponseFromServer);
            }
        }
    }
}
catch (Exception ex)
{
    Response.Write(ex.Message);
}

Notifications are not working on iPhone with my server side code but I get a good response from Firebase.

    {
    "multicast_id": 479608 XXXXXX529964,
    "success": 1,
    "failure": 0,
    "canonical_ids": 0,
    "results": [{
        "message_id": "0:1467935842135743%a13567c6a13567c6"
    }]
}

Any help or suggestions would be really appreciated.

回答1:

Try setting the priority field to High in your FCM request.

Eg:

var data = new
{
    to = deviceId,
    notification = new
    {
        body = "This is the message",
        title = "This is the title",
        icon = "myicon"
    },
    priority = "high"
};

Note though that using high priority in development is fine but in production it should only be used when the user is expected to take action, like reply to a chat message.