[英]Firestore Messaging: Sending message to Topic with Swift
我正在將我的iOS應用程序從CloudKit轉換為Firestore。 到目前為止,除通知外,其他所有功能都運行良好。 我讓用戶訂閱了特定主題,如果我使用該網站發送消息,該主題將非常有用。
但是,我需要我的iOS應用程序才能發送消息,而google提供了有關如何執行此操作的出色文檔。 他們的指示是
(Send to a single Topic)
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
Content-Type: application/json
Authorization: Bearer (Server Key)
{
"message":{
"topic" : "foo-bar",
"notification" : {
"body" : "This is a Firebase Cloud Messaging Topic Message!",
"title" : "FCM Message"
}
}
}
因此,為了做到這一點,我決定使用一個http請求來發布該信息。 這是我的代碼...
let json: [String: Any] = ["message": ["topic":"\(Items.sharedInstance.clubSelected2.id)", "notification":["body":"Test Body","title":"Test Title"]]]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
let url = URL(string: "https://fcm.googleapis.com/v1/projects/(My Project)/messages:send")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer (My Server Key)", forHTTPHeaderField: "Authorization")
request.httpMethod = "POST"
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
// check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
有了所有這些,我將收到錯誤消息“請求具有無效的身份驗證憑據。預期的OAuth 2訪問令牌,登錄cookie或其他有效的身份驗證憑據。請參閱https://developers.google.com/identity/sign-in/web/devconsole -project 。\\“。 我創建了新的服務器密鑰,但仍然收到相同的錯誤。 以下是我在“授權”字段中嘗試過的內容...當然沒有括號
可以解決此授權錯誤的任何幫助將不勝感激!
FCM v1不會僅從服務器發送來自客戶端的消息。 您需要使用XMPP直接從客戶端發送傳出消息。 就個人而言,我更喜歡從服務器發送。 您可以向服務器發送傳出請求以處理該消息,或者觸發雲功能自動運行。
如果要使用FCM最新版本FCM v1,則需要從服務器發送。 Firebase提供了Admin SDK ,使您可以在服務器端訪問Firebase產品。 然后,您不必處理生成憑據或構建請求。
當通過POST請求而不是通過Admin SDK使用FCM v1端點時,將使用服務帳戶密鑰JSON文件生成FCM v1的憑據。 請參閱指南中的說明 。 您可以在此處從Firebase控制台下載文件。 選擇您的項目以轉到儀表板中的位置。 該指南中包括用於從文件中獲取憑據的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.