ios - 我尝试在 iPhone 的后台显示 FCM 通知,但是当我使用 Swift 发送此通知时它不起作用

标签 ios swift iphone push-notification firebase-cloud-messaging

我尝试在 iPhone 的后台显示 Firebase Cloud Messaging 的通知,但是当我使用 Swift 发送此通知时它不起作用。

我在 Postman 中使用 HTTP 请求向我的 iPhone 发送了 FCM,这一切正常:我的 iPhone 在后台正确显示通知。

当我使用 Swift 发出相同的 HTTP 请求时,Firebase 的响应很好,但我的 iPhone 什么也不显示。

Postman 中有请求和响应:
Postman's screenshot

Swift Playground 中有相同的请求:

import Foundation

let key = "key=<my-server-key>"
let singleMessageUrl = "https://fcm.googleapis.com/fcm/send"

func sendSingleMessage() {
    let params: [String: Any] = [
        "to": "<my-device-token>",
        "notificiation": [
            "title": "Push from my playground",
            "body": "Push from my playground !"
        ],
    ]
    guard let bodyNotif = try? JSONSerialization.data(withJSONObject: params, options: []) else {
        print("BAD NOTIF")
        return
    }
    guard let json = try? JSONSerialization.jsonObject(with: bodyNotif, options: []) as? [String: Any] else {
        print("BAD JSON")
        return
    }
    print("PARAMS REQUEST:\n", params)
    print("---------------------------")
    print("JSON REQUEST:\n", json)
    print("---------------------------")
    guard let url = URL(string: singleMessageUrl) else {
        print("BAD URL")
        return
    }
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = bodyNotif
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue(key, forHTTPHeaderField: "Authorization")
    URLSession.shared.dataTask(with: request) { (data, response, error) in
        if let error = error {
            print("ERROR", error.localizedDescription)
        }
        guard let response = response else { return }
        print("HEADERS RESPONSE:\n", response)
        print("---------------------------")
        guard let data = data else { return }
        guard let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
            print("BAD JSON RESPONSE")
            return
        }
        print("BODY RESPONSE:\n", json)
    }.resume()
}
sendSingleMessage()

当我启动上述请求时,控制台中的响应似乎正常:
PARAMS REQUEST:
 ["to": "<my-device-token>", "notificiation": ["title": "Push from my playground", "body": "Push from my playground !"]]
---------------------------
JSON REQUEST:
 ["to": <my-device-token>, "notificiation": {
    body = "Push from my playground !";
    title = "Push from my playground";
}]
---------------------------
HEADERS RESPONSE:
 <NSHTTPURLResponse: 0x7fcaf544c610> { URL: https://fcm.googleapis.com/fcm/send } { Status Code: 200, Headers {
    "Cache-Control" =     (
        "private, max-age=0"
    );
    "Content-Encoding" =     (
        gzip
    );
    "Content-Length" =     (
        138
    );
    "Content-Type" =     (
        "application/json; charset=UTF-8"
    );
    Date =     (
        "Sun, 05 Jan 2020 09:47:15 GMT"
    );
    Expires =     (
        "Sun, 05 Jan 2020 09:47:15 GMT"
    );
    Server =     (
        GSE
    );
    "alt-svc" =     (
        "quic=\":443\"; ma=2592000; v=\"46,43\",h3-Q050=\":443\"; ma=2592000,h3-Q049=\":443\"; ma=2592000,h3-Q048=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000"
    );
    "x-content-type-options" =     (
        nosniff
    );
    "x-frame-options" =     (
        SAMEORIGIN
    );
    "x-xss-protection" =     (
        "1; mode=block"
    );
} }
---------------------------
BODY RESPONSE:
 ["multicast_id": <the-multicast_id-send-by-FCM>, "results": <__NSSingleObjectArrayI 0x7ff55bd46aa0>(
{
    "message_id" = "<the-message_id-send-by-FCM>";
}
)
, "success": 1, "failure": 0, "canonical_ids": 0]

但不幸的是,我的 iPhone 在正确接收到 postman 请求发送的通知时,什么也没收到这个 Swift 的请求。

最佳答案

我已经在我的应用程序上检查了此代码 - 它可以 100% 运行。代码本身包含强制解包,并且是从 Postman 复制的,因此将来需要优化,但如果添加设备 token 和服务器 key ,您可以快速检查它。我还测试了您的代码并发现了一个问题 - 您应该更改 "notificiation""notification" .希望这对您有所帮助。

class ViewController: UIViewController {

    var semaphore = DispatchSemaphore (value: 0)
    var request = URLRequest(url: URL(string: "https://fcm.googleapis.com/fcm/send")!,timeoutInterval: Double.infinity)

    override func viewDidLoad() {
        super.viewDidLoad()

        sendSingleMessage()
    }

    func sendSingleMessage() {

        let parameters = "{\n    \"to\" : \"<my-device-token>\", \n\n    \"notification\": {\n    \"body\": \"From Swift code message\"\n  }\n\n  }"
        let postData = parameters.data(using: .utf8)

        request.addValue("key=<my-server-key>", forHTTPHeaderField: "Authorization")
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")

        request.httpMethod = "POST"
        request.httpBody = postData

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data else {
                print(String(describing: error))
                return
            }
            print(String(data: data, encoding: .utf8)!)
            self.semaphore.signal()
        }

        task.resume()
        semaphore.wait()
    }

}

关于ios - 我尝试在 iPhone 的后台显示 FCM 通知,但是当我使用 Swift 发送此通知时它不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59598708/

相关文章:

swift - 将通用值参数指定为对象初始化调用的参数

iphone - Cocos2d 应用程序适用于除 iPhone 4(任何操作系统)之外的所有设备,CCBatchnode 在 addchild 后仅显示黑屏

iOS 辅助功能隐藏 "textField, double tap to edit"公告

iOS Cocoapods 文件未找到错误

ios - 处理具有关系的 Firebase 模型的模式 (iOS)

swift - 无法摆脱 UIviewcontroller header

ios - 仅当隐藏文本字段时才使用键盘移动 View

iphone - 如何检测我的 iOS 应用程序是否有更新版本?

iphone - 调整条形图的大小

ios - 允许用户继续在 iOS 应用程序中收听他们的音乐