1

Is it possible to use Firebase's FCM to send apns push notifications to an ios device?

Desired Workflow:

iOS app sends request to my .NET server to provide it the push token. My .NET server will handle all push notifications. So I assume this would be http requests to firebase and firebase would send out the notification?

Is this workflow possible?

user6728767
  • 1,123
  • 3
  • 15
  • 31

4 Answers4

0

I have worked with Android Applications using Firebase's FCM.. so i think there must be way to work with ios.

here is the snippet of code for sending push notification using fcm in c#.

 NotifBooking objnotif = new NotifBooking();
      string ApplicationID = "AIzaSyCBM20ZXXXXXXXXXXjog3Abv88";
                        string SENDER_ID = "962XXXXXXX";

                        var value = "Alert :" + Message + ""; //message text box

                        WebRequest tRequest;

                        tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "post";
                        tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                        tRequest.Headers.Add(string.Format("Authorization: key={0}", ApplicationID)); tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));


                        tRequest.ContentType = "application/json";
                        var data1 = new
                        {


                            to = "" + dt.Rows[i]["RegId"].ToString().Trim() + "",//Device RegID
                            priority = "high",
                            notification = new
                            {
                                body = Message,
                                title = Heading,
                                is_background = true,
                                image = "abc.com/images/1_icon.png",
                                appicon = "abc.com/images/1_icon.png",
                                sound = "default"
                            },

                            data = new
                            {
                                //body = Message,
                                //is_background=false,
                                //title = "Test FCM",

                                //appicon = "myicon",
                                image = "abc.com/images/1_icon.png"
                            },

                        };
                        Console.WriteLine(data1);
                        var serializer = new JavaScriptSerializer();
                        var json = serializer.Serialize(data1);

                        Byte[] byteArray = Encoding.UTF8.GetBytes(json);

                        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();
                                        string str = sResponseFromServer;

                                    }
                                }
                            }
                        }

                        objnotif.data = json;
                    }
Vipin G
  • 169
  • 1
  • 8
  • Did you have to install anything on your android app for this to work? I just want my app to send an http request to my server to "register" for push notifications. Then the server pushes to the app. – user6728767 Apr 13 '18 at 06:24
  • nothing to install but need to configure app using application id and senderid...i am not into android stuff but this link may help http://androidbash.com/firebase-push-notification-android/ – Vipin G Apr 13 '18 at 09:03
0

You should get device token from Firebase and register the current user in backend side with the same token.

After that, you can send push notifications from your backend.

Put this code in AppDelegate class.

Call InitAPNS() from FinishedLaunching.

    public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
    {
        //TODO: save token and register one in backend side
        Settings.DeviceTokenFCM = InstanceId.SharedInstance.Token;
    }

    public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
    {
        ShowPushMessage(userInfo);
    }

    private void ShowPushMessage(NSDictionary userInfo)
    {
        if (userInfo != null)
        {
            try
            {
                var apsDictionary = userInfo["aps"] as NSDictionary;
                var alertDictionary = apsDictionary?["alert"] as NSDictionary;
                var body = alertDictionary?["body"].ToString();
                var title = alertDictionary?["title"].ToString();

                var window = UIApplication.SharedApplication.KeyWindow;
                var vc = window.RootViewController;

                var alert = UIAlertController.Create(title, body, UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Cancel, null));

                vc.PresentViewController(alert, animated: true, completionHandler: null);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }
    }

    private void InitAPNS()
    {
        // Monitor token generation
        InstanceId.Notifications.ObserveTokenRefresh(TokenRefreshNotification);

        if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
        {
            UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.Sound, (granted, error) =>
            {
                if (granted)
                {
                    InvokeOnMainThread(UIApplication.SharedApplication.RegisterForRemoteNotifications);
                }
            });
        }
        else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
        {
            var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
                    UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
                    new NSSet());

            UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
            UIApplication.SharedApplication.RegisterForRemoteNotifications();
        }
        else
        {
            UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
            UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
        }

        Firebase.Core.App.Configure();
    }

    private void TokenRefreshNotification(object sender, NSNotificationEventArgs e)
    {
        ConnectToFCM();
    }

    private void ConnectToFCM()
    {
        var tokenFirebase = InstanceId.SharedInstance.Token;

        ////registation token in background thread
        System.Threading.Tasks.Task.Run(() =>
        {
            if (!string.IsNullOrEmpty(tokenFirebase))
            {
                Firebase.CloudMessaging.Messaging.SharedInstance.SetApnsToken(tokenFirebase, ApnsTokenType.Production);
            }
        });

        Messaging.SharedInstance.ShouldEstablishDirectChannel = true;
    }
Anastasia
  • 452
  • 5
  • 7
0

I have worked with Android Applications using Firebase's FCM..


    namespace pushios.Controllers
    {

    public class HomeController : ApiController
        {
            [HttpGet]

    [Route("sendmessage")]

            public IHttpActionResult SendMessage()
          {
                var data = new {
                    to = "xxxxxxxxxxxxxxxxxxx",
                    data = new
                    {
                        body="Test",
                        confId= "6565",
                        pageTitle= "test",
                        pageFormat= "",
                        dataValue= "",
                        title= "C#",
                        webviewURL= "",
                        priority = "high",
                        notificationBlastID = "0",
                        status = true
                    }
                };
                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;
                }

            }
        }
    }
    ```


0

IOS push Notification using C#.I have worked with Android Applications using Firebase's FCM.here is the snippet of code for sending push notification using fcm in c#.

**

namespace push
{
    public partial class pushios : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
             SendPushNotification(txtDeviceToken.Text, txtMessage.Text);
        }
        private void  SendPushNotification(string deviceToken,string message)
        {
               try
        {
            //Get Certificate
            var appleCert = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Files/Certificate/IOS/Production_Certificate.p12"));
            // Configuration (NOTE: .pfx can also be used here)
            var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, appleCert, "1234567890");
            // Create a new broker
            var apnsBroker = new ApnsServiceBroker(config);
            // Wire up events
            apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
            {
                aggregateEx.Handle(ex =>
                {
                    // See what kind of exception it was to further diagnose
                    if (ex is ApnsNotificationException)
                    {
                        var notificationException = (ApnsNotificationException)ex;
                        // Deal with the failed notification
                        var apnsNotification = notificationException.Notification;
                        var statusCode = notificationException.ErrorStatusCode;
                        string desc = $"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}";
                        Console.WriteLine(desc);
                        Label1.Text = desc;
                    }
                    else
                    {
                        string desc = $"Apple Notification Failed for some unknown reason : {ex.InnerException}";
                        // Inner exception might hold more useful information like an ApnsConnectionException           
                        Console.WriteLine(desc);
                        Label1.Text = desc;
                    }
                    // Mark it as handled
                    return true;
                });
            };
            apnsBroker.OnNotificationSucceeded += (notification) =>
            {
                Label1.Text = "Apple Notification Sent successfully!";
            };
            var fbs = new FeedbackService(config);
            fbs.FeedbackReceived += (string devicToken, DateTime timestamp) =>
            {

            };

            apnsBroker.Start();
            if (deviceToken != "")
            {
                apnsBroker.QueueNotification(new ApnsNotification
                {
                    DeviceToken = deviceToken,
                    Payload = JObject.Parse(("{\"aps\":{\"badge\":1,\"sound\":\"oven.caf\",\"alert\":\"" + (message + "\"}}")))
                });
            }
            apnsBroker.Stop();
        }
        catch (Exception)
        {
            throw;
        }
        }
    }

**