在应用被终止后使用 HTTP 请求通过 Firebase (FCM) 向 iOS 设备发送推送通知

Send push notification to iOS device via Firebase (FCM) using HTTP Request after app is killed

应用程序被终止后,我无法通过 HTTP 请求通过 Firebase 向我的 iOS 设备发送推送通知。当应用程序在前台或在后台处于活动状态时,一切都按预期工作。但是,如果我终止该应用程序,它将无法正常工作。如果应用程序被终止,我可以通过 Firebase 控制台向我的应用程序发送通知,所以我相信我使用的代码一定有问题。

这是我发送推送通知的代码:

    private void SendPushNotification(string devicetoken, string header, string content, string pushdescription)
    {
        var textNotification = new
        {
            to = devicetoken,
            notification = new
            {
                title = header,
                text = content,
                content_available = true,
                sound = "enabled",
                priority = "high",
                id = pushdescription,
            },
            project_id = "rrp-mobile",
        };

        var senderId = "212579566459";
        var notificationJson = Newtonsoft.Json.JsonConvert.SerializeObject(textNotification);
        using (var client = new WebClient())
        {
            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.Authorization] = "key=AIfrSyAtgsWCMH4s_bOyj-Us4CrdsifHv-GqElg";
            client.Headers["Sender"] = $"id={senderId}";
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.UploadString("https://fcm.googleapis.com/fcm/send", "POST", notificationJson);
        }
    }

我是不是忘记了什么?这适用于在前台、后台和应用程序被杀死时向 Android 设备发送推送通知,就像我所说的在前台和后台向 iOS 设备发送推送通知。

唯一的问题是当应用被终止时向 iOS 设备发送推送通知。有谁知道我将如何解决这个问题?

我刚刚意识到我的错误,而且很简单。我在这里发布这个是因为我相信这可能是一件容易错过的事情。

    var textNotification = new
    {
        to = devicetoken,
        notification = new
        {
            title = header,
            text = content,
            content_available = true,
            sound = "enabled",
            **priority = "high",**
            id = pushdescription,
        },
        project_id = "rrp-mobile",
    };

您需要确保优先级 属性 定义在 "notification" 范围之外,如下所示:

    var textNotification = new
    {
        to = devicetoken,
      **priority = "high",**
        notification = new
        {
            title = header,
            text = content,
            content_available = true,
            sound = "enabled",
            id = pushdescription,
        },
        project_id = "rrp-mobile",
    };

这将使您的推送通知即使在应用程序被终止时也能发送。