FCM PushNotification从.NET到iOS设备

时间:2018-04-12 21:48:23

标签: asp.net firebase apple-push-notifications firebase-cloud-messaging

是否可以使用Firebase的FCM向ios设备发送apns推送通知?

所需的工作流程:

iOS应用程序向我的.NET服务器发送请求以向其提供推送令牌。我的.NET服务器将处理所有推送通知。所以我假设这是对firebase的http请求,firebase会发出通知吗?

这个工作流程是否可行?

4 个答案:

答案 0 :(得分:0)

我使用Firebase的FCM使用Android应用程序..所以我认为必须有办法使用ios。

这是用于在c#中使用fcm发送推送通知的代码片段。

 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;
                    }

答案 1 :(得分:0)

您应该从Firebase获取设备令牌,并在后端使用相同的令牌注册当前用户。

之后,您可以从后端发送推送通知。

将此代码放在AppDelegate类中。

FinishedLaunching 调用 InitAPNS()

    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;
    }

答案 2 :(得分:0)

我曾经使用Firebase的FCM处理Android应用程序。

implementation 'androidx.appcompat:appcompat:1.1.0-alpha05'

答案 3 :(得分:0)

使用C#的iOS推送通知。我已经使用Firebase的FCM与Android应用程序一起工作。这是在c#中使用fcm发送推送通知的代码段。

**

ALTER PROCEDURE [dbo].[spc_Schedule_Update_Qty_Stock]
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    UPDATE      item
    SET         QtyOnHand = CASE WHEN (inv.QtyOnHand - inv.QtyAllocated) < 0 THEN 0 ELSE (inv.QtyOnHand - inv.QtyAllocated) END--inv.QtyOnHand
    FROM        tb_Item item WITH (NOLOCK)
    INNER JOIN  [105.255.132.248].SysproCompanyA.dbo.InvWarehouse inv WITH (NOLOCK)
    ON          inv.StockCode = item.sCode  COLLATE SQL_Latin1_General_CP1_CI_AS 
    WHERE       inv.Warehouse in ('J','JT')
END

**