FCM 推送通知从 .NET 到 iOS 设备



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

所需工作流程:

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

这个工作流程可行吗?

我使用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;
                    }

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

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

将此代码放在 AppDelegate 类中。

DoneLaunching 调用 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;
    }

使用 C# 的 IOS 推送通知。我曾使用Firebase的FCM使用Android应用程序.这是在c#中使用fcm发送推送通知的代码片段。

**

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

**

我使用Firebase的FCM使用Android应用程序。


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

相关内容

  • 没有找到相关文章

最新更新