use*_*242 5 ios firebase swift firebase-cloud-messaging
我在iOS上使用Firebase并且正在尝试实施主题.我知道如何订阅和取消订阅:
Messaging.messaging().subscribe(toTopic: "myTopic")
Messaging.messaging().unsubscribe(fromTopic: "myTopic")
Run Code Online (Sandbox Code Playgroud)
我的问题是,我怎么知道我订阅了哪些主题?如何取消订阅我订阅的所有主题?如何从Firebase访问所有主题?
我设法在 iOS 中通过GET向以下地址发送请求来做到这一点https://iid.googleapis.com/iid/info:
解码响应模型:
struct AppInstance: Codable {
let applicationVersion: String
let gmiRegistrationId: String
let application: String
let scope: String
let authorizedEntity: String
let rel: Rel
let platform: String
}
struct Rel: Codable {
let topics: [String: AddDate]
enum CodingKeys: String, CodingKey {
case topics
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
topics = try container.decode([String: AddDate].self, forKey: .topics)
}
}
struct AddDate: Codable {
let addDate: String
}
Run Code Online (Sandbox Code Playgroud)
然后调用如下函数:
func getSubscribedTopics() async -> [String]? {
let fcmToken = "YOUR_FCM_TOKEN" // received inside didReceiveRegistrationToken callback
guard var urlComponents = URLComponents(string: "https://iid.googleapis.com/iid/info/\(fcmToken)")
else { return nil }
let parameter = URLQueryItem(name: "details", value: "true")
urlComponents.queryItems = [parameter]
guard let url = urlComponents.url else { return nil }
let serverKey = "YOUR_SERVER_KEY" // from firebase console
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue("Bearer \(serverKey)", forHTTPHeaderField: "Authorization") // this will be deprecated
let (data, _) = try! await URLSession.shared.data(for: request)
let decoder = JSONDecoder()
let appInstance = try! decoder.decode(AppInstance.self, from: data)
let topics = appInstance.rel.topics.keys.map { $0 as String }
return topics
}
Run Code Online (Sandbox Code Playgroud)
目前该功能有效,但使用服务器密钥进行授权将在 2024 年 6 月被弃用。我应该用令牌替换服务器密钥,但这对我不起作用,服务器响应为“未经授权”。
| 归档时间: |
|
| 查看次数: |
1957 次 |
| 最近记录: |