如何在Firebase - iOS上查找和取消订阅主题?

qoefvg9y  于 2023-06-24  发布在  iOS
关注(0)|答案(1)|浏览(101)

我在iOS上使用Firebase,并试图实现主题。我知道如何订阅和退订:

Messaging.messaging().subscribe(toTopic: "myTopic")

Messaging.messaging().unsubscribe(fromTopic: "myTopic")

我的问题是,我如何知道我订阅了哪些主题?如何取消订阅我订阅的所有主题?如何从Firebase访问所有主题?

lymnna71

lymnna711#

在iOS中,我通过向https://iid.googleapis.com/iid/info发送GET请求来做到这一点:
用于解码响应的模型:

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
}

然后调用以下函数:

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
}

这目前正在工作,但使用服务器密钥进行授权将在2024年6月被弃用。我应该用令牌替换服务器密钥,但这对我不起作用,服务器回答“Unauthorized”。

相关问题