【问题标题】:I try to display FCM notification in background on my iPhone but it doesn't work when I send this notification with Swift我尝试在 iPhone 的后台显示 FCM 通知,但是当我使用 Swift 发送此通知时它不起作用
【发布时间】:2020-04-23 04:56:59
【问题描述】:

我尝试在我的 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 没有收到这个 Swift 的请求,而它正确地收到了邮递员请求发送的通知。

【问题讨论】:

  • 欢迎来到 StackOverflow。您是否尝试设置 content_available: truepriority: high 参数?正如这里提到的stackoverflow.com/a/39581650/634958
  • 是的,我试过了,问题还是一样

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


【解决方案1】:

我已在我的应用程序上检查了此代码 - 它 100% 有效。代码本身包含强制解包,并且是从 Postman 复制的,因此将来需要对其进行优化,但是如果添加设备令牌和服务器密钥,您可以快速检查它。此外,我测试了您的代码并发现了一个问题 - 您应该将 "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()
    }

}

【讨论】:

    猜你喜欢
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多