快速地,需要关于从 de API Cloud Messaging Legacy 迁移到 Firebase HTTP V1 的承载的精确度

问题描述 投票:0回答:1

这是我发送 HTTP V1 推送通知的新方法: 我之前用过旧版。

    func sendPushNotification(to token: String, title: String, body: String) {
        //let urlString = "https://fcm.googleapis.com/fcm/send"
        let urlString = "fcm.googleapis.com/v1/projects/myproject-77a88/messages:send"
        let url = NSURL(string: urlString)!
        let paramString: [String : Any] = ["to" : token, "notification" : ["title" : title, "body" : body, "badge": "1", "sound": "default"]
        ]
        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"
        request.httpBody = try? JSONSerialization.data(withJSONObject:paramString, options: [.prettyPrinted])
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("key=\(KSERVERKEY)", forHTTPHeaderField: "Authorization")
        let task =  URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
            do {
                if let jsonData = data {
                    if let jsonDataDict  = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
                        NSLog("Received data:\n\(jsonDataDict)")
                    }
                }
            } catch let err as NSError {
                print(err.debugDescription)
            }
        }
        task.resume()
    }

我将 UrlString 更改为:

"https://fcm.googleapis.com/fcm/send"

"fcm.googleapis.com/v1/projects/myproject-77a88/messages:send"

以及从旧版本到新版本的令牌

https://console.cloud.google.com/iam-admin/serviceaccounts/

这是 firebase 解释这些内容的页面: https://firebase.google.com/docs/cloud-messaging/migrate-v1?hl=fr

如果理解得好的话,每次发送推送通知时,承载者都会不同。持有者是暂时的。 但即使我阅读了 Firebase 文档中的解释,我也不知道如何每次检索新的承载者。 有人可以帮忙吗。

swift firebase push-notification firebase-cloud-messaging
1个回答
0
投票

最后,这是检索承载并发送推送通知的代码:

class PushNotificationSender {
    let API_Key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    func getFirebaseBearerToken(completion: @escaping (String?) -> Void) {
            guard let url = URL(string: "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=\(API_Key)") else {
                completion(nil)
                return
            }
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            let task = URLSession.shared.dataTask(with: request) { data, response, error in
                guard let data = data, error == nil else {
                    completion(nil)
                    return
                }
                do {
                    if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
                       let idToken = json["idToken"] as? String {
                        completion(idToken)
                    } else {
                        completion(nil)
                    }
                } catch {
                    completion(nil)
                }
            }
            task.resume()
        }
    func sendPushNotification(to token: String, title: String, body: String) {
            getFirebaseBearerToken { bearerToken in
                guard let bearerToken = bearerToken else {
                    print("Failed to retrieve Bearer token.")
                    return
                }
                
                let urlString = "https://fcm.googleapis.com/v1/projects/myprojectID-99a99/messages:send"

                guard let url = URL(string: urlString) else {
                    print("@@Invalid URL")
                    return
                }

                let payload: [String: Any] = [
                    "message": [
                        "token": token,
                        "notification": [
                            "title": title,
                            "body": body
                        ]
                    ]
                ]

                let jsonData = try? JSONSerialization.data(withJSONObject: payload)

                var request = URLRequest(url: url)
                request.httpMethod = "POST"
                request.httpBody = jsonData
                request.setValue("Bearer \(bearerToken)", forHTTPHeaderField: "Authorization")
                request.setValue("application/json", forHTTPHeaderField: "Content-Type")

                let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
                    if let error = error {
                        print("Error: \(error.localizedDescription)")
                        return
                    }

                    if let data = data {
                        do {
                            let responseJSON = try JSONSerialization.jsonObject(with: data, options: [])
                            print("Response: \(responseJSON)")
                        } catch {
                            print("Error parsing response JSON: \(error.localizedDescription)")
                        }
                    }
                }
                task.resume()
            }
        }
}

所以发送的代码是:

let pushSender = PushNotificationSender()
pushSender.sendPushNotification(to: "DEVICE_TOKEN", title: "Hello", body: "Sample Notification")

如果 Firebase SDK 安装在 Package Dependencies 中,则无需检索 de bearer。 Firebase 自己管理。否则,可以使用我的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.