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

I try to display FCM notification in background on my iPhone but it doesn't work when I send this notification with Swift

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

我在 Postman 中通过 HTTP 请求向我的 iPhone 发送了一个 FCM,并且工作正常:我的 iPhone 在后台正确显示了通知。

当我使用 Swift 发出相同的 HTTP 请求时,Firebase 的响应正常,但我的 iPhone 没有显示任何内容。

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

Swift 游乐场中有相同的请求:

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 没有收到此 Swift 的请求,但它正确收到了邮递员请求发送的通知。

我已经在我的应用程序上检查了这段代码 - 它 100% 有效。代码本身包含一个force unwrapping,是从Postman复制过来的,所以以后需要优化,但是如果加上device token和server 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()
    }

}