Firebase Cloud Messaging and C# server side code

纵然是瞬间 提交于 2020-01-13 11:44:34

问题


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.




回答2:


I am using FCM in android and IOS push notification.I am using Visual Studio 2015.To be create a web api project and a to add a controller.write the code.Code is given below

using System;
using System.Net;
using System.Web.Http;
using System.Web.Script.Serialization;
using System.Configuration;
using System.IO;



namespace pushios.Controllers
{
    public class HomeController : ApiController
    {
        [HttpGet]
        [Route("sendmessage")]

        public IHttpActionResult SendMessage()
        {
            var data = new {
                to = "device Tokens", // iphone 6s test token
                data = new
                {
                    body = "test",
                    title = "test",
                    pushtype="events",



                },
                notification = new {
                        body = "test",
                        content_available = true,
                         priority= "high",
                        title = "C#"
               }



        } ;
            SendNotification(data);
          return Ok();
        }
        public void SendNotification(object data)
        {
            var Serializer = new JavaScriptSerializer();
            var json = Serializer.Serialize(data);
            Byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(json);

            SendNotification(byteArray);
        }
        public void SendNotification(Byte[] byteArray)
        {

            try
            {
                String server_api_key = ConfigurationManager.AppSettings["SERVER_API_KEY"];
                String senderid = ConfigurationManager.AppSettings["SENDER_ID"];

                WebRequest type = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
                type.Method = "post";
                type.ContentType = "application/json";
                type.Headers.Add($"Authorization: key={server_api_key}");
                type.Headers.Add($"Sender: id={senderid}");

                type.ContentLength = byteArray.Length;
                Stream datastream = type.GetRequestStream();
                datastream.Write(byteArray, 0, byteArray.Length);
                datastream.Close();

                WebResponse respones = type.GetResponse();
                datastream = respones.GetResponseStream();
                StreamReader reader = new StreamReader(datastream);

                String sresponessrever = reader.ReadToEnd();
                reader.Close();
                datastream.Close();
                respones.Close();

            }
            catch (Exception)
            {
                throw;
            }

        }
    }
}

In the case of android json is given below

var data = new {
                    to = "device Tokens", // iphone 6s test token
                    data = new
                    {
                        body = "test",
                        title = "test",
                        pushtype="events",



                    };

In the case of IOS json

var data = new {
                    to = "device Tokens", // iphone 6s test token
                    data = new
                    {
                        body = "test",
                        title = "test",
                        pushtype="events",



                    },
                    notification = new {
                            body = "test",
                            content_available = true,
                             priority= "high",
                            title = "C#"
                   }



            } ;

SERVER_API_KEY,SENDER_ID I am adding the web config.To be collect SERVER_API_KEY,SENDER_ID in FCM.

<add key="SERVER_API_KEY" value="ADD Key in FCM"/>
    <add key="SENDER_ID" value="Add key in fcm "/>


来源:https://stackoverflow.com/questions/38257160/firebase-cloud-messaging-and-c-sharp-server-side-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!